I just noticed that you can not use standard math operators on an enum such as ++ or +=
So what is the best way to iterate through all of the values in a C++ enum?
I just noticed that you can not use standard math operators on an enum such as ++ or +=
So what is the best way to iterate through all of the values in a C++ enum?
You can try and define the following macro:
Now you can use it:
It can be used to iterate backwards and forwards through unsigned, integers, enums and chars:
Despite its awkward definition it is optimized very well. I looked at disassembler in VC++. The code is extremely efficient. Don't be put off but the three for statements: the compiler will produce only one loop after optimization! You can even define enclosed loops:
You obviously cannot iterate through enumerated types with gaps.
C++ doesn't have introspection, so you can't determine this kind of thing at run-time.
I often do it like that
or if not successive, but with regular step (e.g. bit flags)
In Bjarne Stroustrup's C++ programming language book, you can read that he's proposing to overload the
operator++
for your specificenum
.enum
are user-defined types and overloading operator exists in the language for these specific situations.You'll be able to code the following:
test code: http://cpp.sh/357gb
Mind that I'm using
enum class
. Code works fine withenum
also. But I preferenum class
since they are strong typed and can prevent us to make mistake at compile time.too much complicated these solution, i do like that :