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