简体   繁体   中英

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

Could one write a function that returns the number of elements in an enum? For example, say I have defined:

enum E {x, y, z};

Then f(E) would return 3.

Nope.

If there were, you wouldn't see so much code like this:

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

Note that this code is also a hint for a (nasty) solution -- if you add a final "guard" element, and don't explicitly state the values of the enum fields, then the last "COUNT" element will have the value you're looking for -- this happens because enum count is zero-based:

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

There are ways, but you have to work... a bit :)

Basically you can get it with a macro.

DEFINE_NEW_ENUM(MyEnum, (Val1)(Val2)(Val3 = 6));

size_t s = count(MyEnum());

How does it work ?

#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_); }

Note that length could also be a template specialization or anything. I dont know about you but I really like the expressiveness of a "Sequence" in BOOST_PP ;)

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

Not without kludging anyway.

Even that trick about with a final entry only works if none of the values are non-default. Eg,

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

不可以。首先,你不能把类型作为参数(只是类型的实例)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM