Doing this in C++ usually requires a special sentinel value inside the enumeration or some preprocessor magic.
If your enumerators are sequential then you can use a simple sentinel value (end
in this case):
enum my_enum {
a,
b,
c,
my_enum_end,
};
for (int i = 0; my_enum_end != i; ++i) {
// Loop through all of the enum values.
}
When the enumeration is more complicated and there are gaps between each of the enumerators then you can use the preprocessor:
#define ENUMS(F) F(a, 1) F(b, 5) F(c, 10)
#define AS_ENUM(ID, V) ID = V,
#define AS_VALUE(ID, V) V,
#define AS_ID(ID, V) #ID,
enum my_enum {
ENUMS(AS_ENUM)
};
my_enum const my_enum_values[] = {ENUMS(AS_VALUE)};
std::string const my_enum_keys[] = {ENUMS(AS_ID)};
for (my_enum const i : my_enum_values) {
// Loop through all of the enum values.
}
for (auto const& i : my_enum_keys) {
// Loop through all of the enum keys.
}
Here all of the enumerators are specified in the ENUMS
macro rather than inside the enum
definition directly.