Looping Through C++ Enums
May 18th, 2007
Here's a trick you can do 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 easily enumerate the enum values.