May 18, 2007

Looping through C++ enums

Perhaps this is obvi­ous 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 con­di­tional check­ing or integer-to-enum cast­ing which becomes unsightly and dif­fi­cult. Instead, simply over­load the ++ oper­a­tor 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 prop­erly and you can enu­mer­ate away.