I have a enumerated type StackID
, and I am using the enumeration to refer to an index of a particular vector and it makes my code easier to read.
However, I now have the need to create a variable called nextAvail
of type StackID
. (it actually refers to a particular stackID ). I tried to increment it but in C++, the following is illegal:
nextAvail++;
Which sort of makes sense to me ... because there's no bounds checking.
I'm probably overlooking something obvious, but what's a good substitute?
I also want to link to this question.
Incrementing an enumeration requires a cast to convert the integer result of addition back to the enumeration type, as in: d = day(d + 1);
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.
You can't "increment" an enum, but you can get the next enum: // MyEnum e; MyEnum next = MyEnum.
No, there is not. enum are really the poor thing in C++, and that's unfortunate of course. Even the class enum introduced in C++0x does not address this extensibility issue (though they do some things for type safety at least).
I'm probably overlooking something obvious, but what's a good substitute?
Overloading operator++
:
// Beware, brain-compiled code ahead! StackID& operator++(StackID& stackID) { #if MY_ENUMS_ARE_CONTIGUOUS && I_DO_NOT_WORRY_ABOUT_OVERFLOW return stackID = static_cast<StackID>( ++static_cast<int>(stackID) ); #else switch(stackID) { case value1 : return stackID = value2; case value2 : return stackID = value3; ... case valueN : return stackID = value1; } assert(false); return stackID; // some compilers might warn otherwise #endif } StackID operator++(StackID& stackID, int) { StackID tmp(stackID); ++stackID; return tmp; }
Because enumerations do not have to be contiguous. E.g. take this example:
enum Colors { cRed, // = 0 cBlue, // = 1 cGreen = 3 }
What should happen in this scenario?
Colors color = cBlue; Colors other = color++;
Should other be cGreen
or should it be 2. In that case it's not a valid enumeration member anymore. What about this?
Colors color = cGreen; Colors other = color++;
Should other
be cRed
(wrap around) or 4?
As you can see, being able to increment enumeration values introduces a whole lot of questions and complicates the simple mechanism that they intend to be.
If all you care about is the integer value being incremented, then simply cast to int
and increment that.
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