I am finding that all of my standard techniques for iterating over regular enums unfortunately do NOT work on enum classes since enum classes do not implicitly convert to integers.
NOT a duplicate of How can I iterate over an enum?, since I'm asking about an enum class (ie: a strongly-typed enum) and they are asking about a regular enum (ie: a weakly-typed enum).
This is the most-readable and simplest approach I could come up with, but I am open to other peoples' example solutions.
I find this approach to be easy-to-use, similar to my C approach (making it more-portable and more-recognizable), and suitable to C++. It compiles with the
-Wall -Wextra -Werrorcompiler build options.Read my comments for the
MyErrorType::_COUNTcase above! If you are using the compiler's-Wall -Wextra -Werrorcompiler options but do NOT include this case in the switch statement (since those build options require you to cover ALL enum cases in ALL switch statements!), the compiler will throw the following error and stop! This is a great safety feature to ensure you keep the enum definition and all switch cases in-sync, handling all possible enums in all of your switch statements. Here is the compiler error thrown by LLVM's clang compiler (an alternative to gcc):One more tiny improvement over the code above, for clarity, would be to add
beginandendelements to your enum like this:...so that you can iterate over the enum as follows. The incrementing part of the
forloop still is a bit cumbersome with all of the required casts, but the initial state and end condition check are at least much clearer now, since they useMyErrorType::beginandMyErrorType::end:Related:
enums (as opposed toenum classes): How can I iterate over an enum?enum classes (strongly-typed enums) and regularenums (weakly-typed enums) in C++: How to automatically convert strongly typed enum into int?-Wall -Wextra -Werrorand other build options, from my eRCaGuy_hello_world repo.Other keywords: common way to iterate over enum or enum class in C or C++; best way to iterate over enum class in C++; enum class C++ iterate; c++ iterate over enum class