May 18th, 2007

Looping Through C++ Enums

Perhaps this is obvious to most, but I thought I'd share my trick with C++ enums. Consider:

enum Face {ACE=1, TWO, THREE, ... , QUEEN, KING};

If you want to step through this datatype you can't just do:

Face f; f++;

No, you must do some kind of conditional checking or integer-to-enum casting which becomes unsightly and difficult. Instead, simply overload the ++ operator for the enum type:

Face operator++(Face& f, int) { // int denotes postfix++
  if (f == KING) return f = ACE; // rollover
  int temp = f;
  return f = static_cast<face> (++temp);
}

Now f++ works properly and you can enumerate away.