2

I first initially learnt to program in Java and therefore when working with enums, I could use .values() in order to produce an array of all the values in that specific enum. I've noticed that now learning C++, there is not an equivalent method.

What is the best way to tackle this as I'm sure people have come up with decent workarounds?

edwoollard
  • 12,245
  • 6
  • 43
  • 74
  • 2
    Sidebar/related: http://stackoverflow.com/q/261963/420683 There's no such feature in C++11. You can either add a sentinel enumerator and rely on the contiguity of the enumerators, or use some preprocessor magic. – dyp Mar 13 '14 at 13:52
  • 2
    Enums are meaningful constants in your program. If you don't know at compile time what constants you have, I have bad news for you. It's like forgetting that the constants 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9 make up a digit. That said, `enum` constants are often used to distinguish configuration or give a set of options for each you may need to execute something different. If you can write code that can process an `enum` value, _no matter what is added to it in the future_, you probably didn't want `enum` in the first place. – Shahbaz Mar 13 '14 at 13:54
  • There's not going to be a trivial way to do this. No matter the solution, I think it's all going to be pretty "hackish". – Some programmer dude Mar 13 '14 at 13:55
  • @JoachimPileborg Yeah I was most likely expecting that haha. – edwoollard Mar 13 '14 at 13:55
  • There is no such feature in C++. – segfault Mar 13 '14 at 14:08

1 Answers1

1

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.

Simple
  • 13,992
  • 2
  • 47
  • 47