Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I increment an enum in VS C++ 6.0?

I copy and pasted some code that increments an enum:

myenum++;  

This code worked fine as it was compiled in VS.NET C++ 2003

I am now developing in VS 6.0 and get the error:

error C2676: binary '++' : 'enum ID' does not define this operator or a conversion to a type acceptable to the predefined operator

How can I get this to behave the same in 6.0?

like image 570
T.T.T. Avatar asked Jun 23 '10 22:06

T.T.T.


2 Answers

I see nothing wrong with defining operator++ on a well understood enum. Isn't that the purpose of operator overloading? If the context made no sense (e.g. an enum with holes in it), then of course it doesn't make sense. Defining operator* for a class called Complex that implement complex numbers is not just valid but a great application of mathematical operator overloading in C++!

If the developer defines an enum where operator++ makes obvious and intuitive sense to the clients of that enum, then that's a good application of that operator overload.

enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
inline DayOfWeek operator++(DayOfWeek &eDOW, int)
{
   const DayOfWeek ePrev = eDOW;
   const int i = static_cast<int>(eDOW);
   eDOW = static_cast<DayOfWeek>((i + 1) % 7);
   return ePrev;
}
like image 67
franji1 Avatar answered Sep 29 '22 11:09

franji1


an enum may be intergral but it doesn't mean it covers a continuous range.

This

enum {
  A, 
  B,
  C,
}

May Will default to

enum {
  A = 0, 
  B = A + 1,
  C = B + 1,
}

and so you could get away with

int a = A;
a++;

However if you have

enum {
  A = 2, 
  B = 4,
  C = 8,
}

now +1 ain't gonna work.

Now, if you also had things like

enum {
  FIRST,
  A = FIRST, 
  B,
  C,
  LAST = C
}

then when iterating the enum would you do A and C twice?

What is the purpose of iterating the enum? do you wish to do 'for all' or for some subset, is there actually an order to the enum?

I'd throw them all in a container and iterate that instead

  • unordered - use a set
  • ordered - a vector or list
like image 34
Greg Domjan Avatar answered Sep 29 '22 13:09

Greg Domjan