简体   繁体   中英

How should I loop over an enum class in C++11?

How should I loop over an enum class in C++11? I'm hoping I still don't have to add a final enum value of END but I couldn't get the range based looping to work either.

If you really need to loop over enum class and you want to avoid adding special END symbol, you can define your own traits for this purpose.

template<typename E> struct EnumTraits;

enum class E { V1, V2, V3 };
enum class F { X1, X2, X3 };

template<> struct EnumTraits<E> { static constexpr E LAST = E::V3; };
template<> struct EnumTraits<F> { static constexpr F LAST = F::X3; };

Then you can write for example:

EnumTraits<E>::LAST 

to get "final" value of E. Of course you still need to define arithmetic operations on this class.

You can do processor hack like this:

#define E_INITIALIZER_LIST { E1, E2, E3, E4 }

enum E E_INITIALIZER_LIST;
constexpr E ALL_VALUES_OF_E[] E_INITIALIZER_LIST;

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