Is there a way to find the power (size) of an enum in C ++?

Is it possible to write a function that returns the number of elements in an enumeration? For example, let's say I defined:

enum E {x, y, z}; 

Then f (E) will return 3.

+6
c ++ enums size
source share
4 answers

Nope.

If that were the case, you would not see as much code as this:

 enum E { VALUE_BLAH, VALUE_OTHERBLAH, ... VALUE_FINALBLAH, VALUE_COUNT } 

Note that this code is also a hint for a (unpleasant) solution - if you add the last "guard" element and do not explicitly specify the enum fields, then the last "COUNT" element will have the value you are looking for - this is because enumeration counter is based on a zero value:

 enum B { ONE, // has value = 0 TWO, // has value = 1 THREE, // has value = 2 COUNT // has value = 3 - cardinality of enum without COUNT } 
+18
source share

There are ways, but you need to work ... a little :)

Basically you can get it with a macro.

 DEFINE_NEW_ENUM(MyEnum, (Val1)(Val2)(Val3 = 6)); size_t s = count(MyEnum()); 

How it works?

 #include <boost/preprocessor/seq/enum.hpp> #include <boost/preprocessor/seq/size.hpp> #define DEFINE_NEW_ENUM(Type_, Values_)\ typedef enum { BOOST_PP_SEQ_ENUM(Values_) } Type_;\ size_t count(Type_) { return BOOST_PP_SEQ_SIZE(Values_); } 

Please note that the length can also be specialized or any. I do not know about you, but I really like the expressiveness of "Sequence" in BOOST_PP;)

+4
source share

No, this is a VFAQ, and the answer is NO !!

In any case, without being left without cloning.

Even this final recording trick only works if none of the values ​​is standard. For example,

 enum B { ONE, // has value = 0 TWO, // has value = 1 THREE=8, // because I don't like threes COUNT // has value = 9 } 
+3
source share

Not. First, you cannot take types as parameters (only type instances)

+2
source share

All Articles