As we know, incrementation and decrementation of enum
in C++03 is illegal, because C++03 enum
may not be continuous. But the C++11 standard introduced the new enum class
construction, which, according to Wikipedia, is more type-safe because it isn’t built on any simple countable type. So now, if we have a bounded list of values of an enum, can we write something like
enum class Colors { Black, Blue, White }; // ... Colors color = Colors::White; color++;
and will it work correctly (e.g. incrementation of White
will return Black
and decrementation of Black
will return White
)?
If we can't write such code, do you know any behavior-like classes either from boost
or from Qt
that provide us this feature (correct in- and decrementing)?
You can't "increment" an enum, but you can get the next enum: // MyEnum e; MyEnum next = MyEnum. values()[e. ordinal() + 1];
No. enum s are not designed to "wrap around" in the way you describe by default.
Nothing in the C Standard prevent incrementing variables of enum types. Of course the value of bla is just incremented by 1 , it may correspond to another enumeration value or not, depending on the actual values of the enumeration values in the enum type.
Difference between Enums and Classes An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).
will it work correctly
No. enum
s are not designed to "wrap around" in the way you describe by default.
And C++11's enum class
doesn't guarantee contiguous values, the same as you describe for C++03's enum
.
You can define the wrapping behavior for your particular enum though. This solution assumes that the values are contiguous, like the enum you described.
enum class Colors { Black, Blue, White, END_OF_LIST }; // Special behavior for ++Colors Colors& operator++( Colors &c ) { using IntType = typename std::underlying_type<Colors>::type c = static_cast<Colors>( static_cast<IntType>(c) + 1 ); if ( c == Colors::END_OF_LIST ) c = static_cast<Colors>(0); return c; } // Special behavior for Colors++ Colors operator++( Colors &c, int ) { Colors result = c; ++c; return result; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With