问题
Given a C++11 enum class, is there some templating or other construct to iterate, at compile-time, over the set of all enumerators? Could one define a template to e.g. initialize an array with all possible values of that enum type?
回答1:
One alternative technique is to resort to the pre-processor.
#define ITERATE_MY_ENUM(_) \
_(A,) \
_(B, =3) \
_(C,) \
_(D, =10)
enum MyEnum {
#define DEFINE_ENUM_VALUE(key, value) key value,
ITERATE_MY_ENUM(DEFINE_ENUM_VALUE)
#undef DEFINE_ENUM_VALUE
};
void foo() {
MyEnum arr[] = {
#define IN_ARRAY_VALUE(key, value) key,
ITERATE_MY_ENUM(IN_ARRAY_VALUE)
#udnef IN_ARRAY_VALUE
};
}
Some may consider it ugly, but it still keeps the code DRY.
回答2:
No, there is no such thing. Also note that the enum type can hold not just the values of the enumerators legally, but any combinations of them OR-ed together (vaguely speaking).
You probably could solve the problem using some simple code generator.
Reflecting comment: Here is a good summary of changes in C++11 regarding class enum. Those addressed implicit conversions, control over underlying type, name scoping, but no change of the fundamental nature. Enumerators are still just things close to literals with no discoverable connections. What you ask for would require kind of reflections, AFAIK it's not yet on the horizon.
来源:https://stackoverflow.com/questions/17195352/sequence-of-enumerators-at-compile-time