Counting sequence at compile time

Given the enum C ++ 11 class, is there any kind of pattern or other constructor to repeat at compile time over the set of all counters? Is it possible to define a template, for example. initialize an array with all possible values ​​of this enum type?

0
source share
2 answers

One alternative way is to use a preprocessor.

#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 find this ugly, but it still stores the DRY code.

+3
source

No, this does not happen. Also note that the type of enumeration can contain not only the values ​​of counters legally, but also any combination of OR-ed together (vaguely speaking).

You could probably solve the problem using a simple code generator.

Reflecting the comment: Here is a good summary of the changes in C ++ 11 regarding the list of classes. Those that relate to implicit conversions, control over the base type, definition of names, but not a change in fundamental nature. Enumerators are still just close to literals with no visible links. What you ask for will require some reflections, AFAIK is not yet on the horizon.

+1
source

Source: https://habr.com/ru/post/1486945/


All Articles