Saturday, March 27, 2010

Extending enums

There might come a scenario where you want to include an enum into a another one where the first one is a subset.

#include
struct enum_a {
     enum constant {
         a, b, c, d,
         end_of_enum_a = d
     };
};
struct enum_b : public enum_a {
     enum constant {
         e = end_of_enum_a + 1,
         f, g, h
     };
};
int main() {
     std::printf("enum_a: a(%d), b(%d), c(%d), d(%d)\n",
         enum_b::a, enum_b::b, enum_b::c, enum_b::d);
     std::printf("enum_b: e(%d), f(%d), g(%d), h(%d)\n",
         enum_b::e, enum_b::f, enum_b::g, enum_b::h);
     return 0;
}

Inheritance to the rescue. :-)

1 comment:

Tom Panning said...

This is a useful trick, but it doesn't really extend the enum enum_a::constant. It creates a new enum called enum_b::constant that won't conflict with enum_a::constant. But as far as the compiler is concerned, they are two unrelated constants. If you have a compiler that checks your usage of enums (e.g., gcc with -Wall), you won't be able to mix the constants. For example, it will complain about the following code:
enum_b::constant example = enum_a::c;