Getting size of enum using preprocessor

1k views Asked by At

I am trying to find a way to calculate the length of an enum, other than adding a "COUNT" element at the end of the enum. I have found a way to use the preprocessor as follows.

#include <iostream>
#include <boost/preprocessor/tuple/elem.hpp>

//simple declaration
template <class E>
struct enum_size;

//specialization is done in the macro for each enum created
#define MAKE_ENUM(name, ...) enum name {__VA_ARGS__};   \
  template <>                       \
  struct enum_size<name> {                  \
    static const int value = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__);   \
    };

MAKE_ENUM(my_enum1, a, b, c)
//MAKE_ENUM(my_enum2, a) //triggers compilation error

int main(int argc, char** argv) {
  std::cout << enum_size<my_enum1>::value << std::endl;
}

However when I try to create my_enum2 as above I get a redeclaration error from the compiler (GCC 4.8.3 on CygWin) as follows

main.cpp:16:21: error: redeclaration of 'a'
 MAKE_ENUM(my_enum2, a)
                 ^
main.cpp:9:41: note: in definition of macro 'MAKE_ENUM'
 #define MAKE_ENUM(name, ...) enum name {__VA_ARGS__}; \
                                     ^
main.cpp:15:21: note: previous declaration 'my_enum1 a'
 MAKE_ENUM(my_enum1, a, b, c)
                 ^
main.cpp:9:41: note: in definition of macro 'MAKE_ENUM'
 #define MAKE_ENUM(name, ...) enum name {__VA_ARGS__}; \

If I change the problematic line to MAKE_ENUM(my_enum2, e) then it compiles cleanly. Any ideas what is wrong here and how I can fix it? Thanks in advance!

1

There are 1 answers

2
ForEveR On BEST ANSWER

Variable a has already type my_enum1, you cannot redeclare it. You can fix this by few ways

1) If you have C++11 use enum class, instead of enum.

#define MAKE_ENUM(name, ...) enum class name {__VA_ARGS__};

2) You can just put enum into namespace.