Sequence of enumerators at compile time

你。 提交于 2019-12-13 05:05:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!