tags:

views:

200

answers:

7

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.

A: 

An enumeration is semantically supposed to represent a set of distinct related, values.

So you could have

enum Colour {RED, GREEN, BLUE};

But that should be equivalent to:

enum Colour {GREEN, BLUE, RED};

The problem is that if you increment an enum then those representations are not the same. GREEN++ in the first case is not the same as GREEN++ in the second.

Making your program dependent on the declaration of the enum is a recipe for disaster - maintainers may assume that the order of the enum doesnt matter, introducing many silent bugs.

Visage
but it is possible to explictly assign the values to enums for example `enum Colour {RED = 0, GREEN = 1, BLUE = 2}`. In that case order doesn't matter.
Naveen
True, but then you're going beyond what an enum should be, and crossing into it being a set of key/value pairs.
Visage
@visage - it's not clear what you're suggesting when you say "that should be equivalent", can you elaborate a little?
BeeBand
@BeeBand: Changing the ordering within an enum should not change the behavior of code; but in your case, it will.
egrunin
Sure. The first declaration expresses the fact that there are three colours, red, green and blue. Thats all it says. But the second one says the same. A maintainer of the code may, perfectly reasonably, add a colour, YELLOW, between GREEN and BLUE. But any code that assumed (implicitly or explicitly) that GREEN + 1 = BLUE would then break, silently. In short, enums are for expressing sets of values that have a common attribute (in this case that they're colours), rather than a relationship between them (that green comes before blue, or after red etc...)
Visage
+1  A: 

Enums are going to be type int, so you can cast them. Is this what you're trying to do?

int ndx = (int) StackID.SomeValue;
...
++ndx;

This is going to make someone very confused down the line, of course.

It occurs to me that you're using an enum where you should be using const, or even #define. enum is most appropriate when you have arbitrary values (where the exact value is not meaningful).

egrunin
@egrunin, I think you might be right re. const. My code assums that the exact value is meaningful, and as you ( and other posters ) have suggested, breaks the intended meaning of an enum.
BeeBand
+1  A: 

Casting back and forth to/from int is of course the obvious solution, then you make clear that you understand that the addition is happening "outside" the enum:

nextAvail = static_cast<StackID>(static_cast<int>(nextAvail) + 1);
unwind
Hmm. Yes, that was my other option, I just think all those cast's make the code look kind of messy.
BeeBand
A: 

With respect to oprator++, $5.2.6/1 states- "The type of the operand shall be an arithmetic type or a pointer to a complete object type."

StackID does not fit the bill here. It is of enumeration type.

One option is like this

$5.7/1 - "For addition, either both operands shall have arithmetic or enumeration type, or one operand shall be a pointer to a completely defined object type and the other shall have integral or enumeration type."

enum Possibility {Yes, No, Maybe};

Possibility operator++(Possibility const& r){
   return Possibility(r + 1);   // convert r to integer, add 1, convert back to Enum
}

int main(){
   Possibility p = Yes;
   Possibility p1 = ++p;
}
Chubsdad
It's pretty obvious (to the poster as well) that this is illegal, the question was what a good substitute was
Andreas Brinck
If you overload __prefix__ increment, you should also always overload __postfix__ increment.
sbi
+7  A: 

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.

Igor Zevaka
@Igor: Now replace your example with this: `enum month ...`. Months are contiguous and naturally increment. What then?
sbi
@sbi: Oh months, that changes everything because months are simple . . . hold on, what happens when you increment December? Should it throw an overflow exception, or should it wrap around? It may be obvious to you what happens, but I may require different functionality. There are too many questions around how this *should* work, the language designers were correct to dis-allow this, and let each case be handled individually.
Binary Worrier
@Igor: Thank you! I think your answer is extremely useful, however I have accepted sbi's. I think I've kind of cheated a little here as I have basically asked 2 questions in my post. One being in the title, and I think you nailed that in your answer and the other being the last line of my post, for which I think the points go to sbi.
BeeBand
@BeeBand Hehe, that's OK. I am glad I provided answers to some of your questions.
Igor Zevaka
@Binary: I'm not sure about your calender, but around here, after December comes January. That's pretty much the same as when you increment `std::numeric_limits<int>::max()`. Anyway, __the question was not about why it is that way__ ("Which sort of makes sense to me..."), __but what to do instead__ ("what's a good substitute?").
sbi
@Sbi: To be honest, I took the question from the title, and didn't read much further. And yes Janurary comes after December, but it's Janurary of *next year*, which may be an imprtant distinction. I'm still glad the language doesn't directly support this, for a variety of reasons :)
Binary Worrier
@Binary: Ouch. Obviously, _I_ failed to read the question's title before I wrote this. Sorry for saying this so self-opinionated. I feel bad about that now. `:(`
sbi
@sbi: nay worries pal. If we weren't opinionated we wouldn't contribute so much on SO :) Enjoy the vacation dude ... that said SWITCH OFF YOUR COMPUTER AND GO ENJOY YOURSELF!
Binary Worrier
Lol @Binary, he's addict xD
Johannes Schaub - litb
@Binary: @Johannes has a point there, although I'm pretty convinced he's so sure about this because he knows the feeling very well. `:)` Anyway, I had fun, went hiking a lot, but in the morning and evening I tormented my UMTS connection a bit with SO and a few other things. I did not check work stuff, though.
sbi
@sbi: Hiking! Ah man I haven't done any real hiking since I visited Alaska with my brothers and that was 4 1/2 years ago. I'd love to hit the trails again, maybe next summer! Again, enjoy :)
Binary Worrier
+2  A: 

Why not store nextAvail as an int instead if you're going to do arithmetic operations on it?

Another option would be to wrap the enum in your own type and overload operator ++ for it (which also could wrap around or something for instance).

Andreas Brinck
@Andreas, I think that's what I'm after - wrapping the enum in my own type and then I can do what I like to it. Can you point me in the direction of an example?
BeeBand
+4  A: 

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;
}
sbi
@sbi - It would certainly make things simple for me to do this. but what do you say to the posters who suggest that an `enum` is meant to express a set of arbitrary values?
BeeBand
@BeeBand - if there is any use at all for the '++', I assume you have a good reason to go beyond the conventional C++ use of enums as compile-time checked ints. On the other hand, Sbi's code could do with some bound-checking.In Java, enums are just a sort of lightweight classes with unmodifiable members -- it is accepted practice to place methods in them. See http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html.
tucuxi
@BeeBand: I don't agree. Probably five out of ten textbook `enum` examples are something like `enum month { Jan, Feb, ..., Dec };` and thus a perfect example for enenumerations that can increment. During the last >15 years of doing C++, I have overloaded `operator++` for enumerations probably less than five times. But I _have_ done it.
sbi
@sbi: Postfix too?
GMan
+1: Correct answer to the body of the question :)
Binary Worrier
@sbi: You forgot one.
Martin York
sbi