Question

//c++03
enum Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[SCOUNT];

//c++11
enum class Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[(int) Something::SCOUNT];

How can I use enums in this case without casting count of enum to int?

Was it helpful?

Solution

How can I use enums in this case without casting count of enum to int?*

You can't... But you can remove the class from enum class

The class keyword means that you can't implicitly convert between that enum and int Removing the class keyword means your enum will work in the same way as in previous versions of C++. You won't need the cast, but you loose the safety of strongly typed enums by allowing implicit casts to integral values.

//C++11
enum class Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[SCOUNT]; // ERRROR

//C++11
enum Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[SCOUNT]; // OK

You can read more about strongly typed enums here


The other option is to cast it, like you are doing. But you should avoid the old C-style cast and use static_cast<> instead as this has better type safety and is more explicit.

//C++11
enum class Something
{
    S1 = 0,
    S2,
    SCOUNT
};
int arr[static_cast< size_t > ( SCOUNT ) ]; // OK

OTHER TIPS

Actually in the second case, you cannot write that without casting.

Since you have to use cast, what you can do now is to use better cast instead of c-style cast:

int arr[to_integral(Something::SCOUNT)];

where to_integral is defined as:

#include <type_traits> //it is where std::underlying_type is defined

template<typename E>
constexpr auto to_integral(E e) -> typename std::underlying_type<E>::type 
{
   return static_cast<typename std::underlying_type<E>::type>(e);
}

Now this function template is reusable. You can use for any C++11-style enum type. It also deduces the underlying type, so you don't have to mention in your code anymore. See this answer for detailed explanation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top