UnknownError1337
UnknownError1337

Reputation: 1222

c++11 vs c++ - enums differences

//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?

Upvotes: 3

Views: 579

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361462

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.

Upvotes: 5

olevegard
olevegard

Reputation: 5532

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

Upvotes: 10

Related Questions