Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

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.

like image 328
Xavier Avatar asked Oct 03 '12 19:10

Xavier


People also ask

How do I iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Can you iterate through enum class C++?

C++ Enumeration Iteration over an enumThere is no built-in to iterate over enumeration.

What is the syntax for enum in C?

The keyword “enum” is used to declare an enumeration. Here is the syntax of enum in C language, enum enum_name{const1, const2, ....... }; The enum keyword is also used to define the variables of enum type.

Can we use float in enum?

Enums can only be ints, not floats in C# and presumably unityScript.


Video Answer


1 Answers

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.

like image 55
witosx Avatar answered Oct 20 '22 02:10

witosx