Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementation and decrementation of “enum class”

Tags:

c++

enums

c++11

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)?

like image 540
Ivan Akulov Avatar asked Mar 16 '13 15:03

Ivan Akulov


People also ask

How do you increment an enum?

You can't "increment" an enum, but you can get the next enum: // MyEnum e; MyEnum next = MyEnum. values()[e. ordinal() + 1];

Do enums wrap around?

No. enum s are not designed to "wrap around" in the way you describe by default.

Can you increment an enum in C?

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.

What is the difference between a class enum and a regular enum?

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).


1 Answers

will it work correctly

No. enums 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; } 
like image 163
Drew Dormann Avatar answered Sep 20 '22 16:09

Drew Dormann