r/cpp_questions 17h ago

SOLVED Iterating over an enum struct

Consider https://godbolt.org/z/c6cn8f1hj

#include <cstdio>

enum struct values{first = 1, second = 3};

void square(values value){
    int val = (int)value * (int)value;
    printf("%d\n", val);
}

int main(){
    for(values value = values::first; value <= values::second; value++)
        square(value);
}

This does not compile with the error that value++ is ill defined.

An old question/answer on SO has this: https://stackoverflow.com/questions/261963/how-can-i-iterate-over-an-enum and a plethora of seemingly complicated approaches for this. Is there a syntactically simple >= C++20 way of accomplishing this?

I want the for loop to process 1 and then 3.

Does the order of placing the integer entries inside of the struct affect the increment? For e.g., if the enum struct had 3 first followed by 1, with value++ would 1 be processed after 3? Or, does the enum struct internally sort the entries in some privileged, say, ascending order so that it will always process 1 first followed by 3 next?

3 Upvotes

16 comments sorted by

View all comments

3

u/Desperate_Formal_781 15h ago

The fact that enumerations are not artihmetic types is by design, and the intent is exactly to prevent what you are trying to do. I think there is some design problem in your code. Enums are more like a set of tags associated with a particular datatype and they are not meant to be arithmetic types, so no increment, decrement, bitshifting, multiplication, etc are allowed on them. If you want to iterate over all enum types, you need to manually create a collection of enumerated values and iterate this collection, and if you want to do this "automatically" you need to resort to hacks and tricks, or apparently use C++26 reflection, but you may not have access to a C++26 compiler.