Why can't I increment a variable of an enumerated type?

Viewed 52015

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.

10 Answers

Very Simple:

nextAvail = (StackID)(nextAvail + 1);

I've overloaded the ++/-- operator in this way:

enum STATE {STATE_1, STATE_2, STATE_3, STATE_4, STATE_5, STATE_6};

// Overload the STATE++ operator

inline STATE& operator++(STATE& state, int) {
    const int i = static_cast<int>(state)+1;
    state = static_cast<STATE>((i) % 6);
    return state;
}

// Overload the STATE-- operator

inline STATE& operator--(STATE& type, int) {
    const int i = static_cast<int>(type)-1;

    if (i < 0) {
        type = static_cast<STATE>(6);
    } else {
        type = static_cast<STATE>((i) % 6);
    }
    return type;
}

I'm quite happy with this C plus C++ solution for a for loop incrementing an enum.

for (Dwg_Version_Type v = R_INVALID; v <= R_AFTER; v++)

=>

int vi;
for (Dwg_Version_Type v = R_INVALID; 
     v <= R_AFTER; 
     vi = (int)v, vi++, v = (Dwg_Version_Type)vi)

The other solutions here are not C backcompat, and quite large.

Related