Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

size

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.

like image 556
rofrankel Avatar asked Feb 02 '10 04:02

rofrankel


3 Answers

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
}
like image 107
Kornel Kisielewicz Avatar answered Nov 15 '22 08:11

Kornel Kisielewicz


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 ;)

like image 31
Matthieu M. Avatar answered Nov 15 '22 07:11

Matthieu M.


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. E.g.,

enum  B {
         ONE,   // has value = 0
         TWO,   // has value = 1
         THREE=8, // because I don't like threes
         COUNT  // has value = 9 
        }
like image 27
Mawg says reinstate Monica Avatar answered Nov 15 '22 06:11

Mawg says reinstate Monica