The size of the array is of a non-integral type when using the C ++ 11 enum class

I used this code:

enum E { E1, E2, E3, MaxNum }; const char * ENames[ MaxNum ] = { "E1", "E2", "E3" }; 

and there were no problems. Now I want to use the "modern" enum class . Now the code is as follows:

 enum class E { E1, E2, E3, MaxNum }; const char * ENames[ E::MaxNum ] = { "E1", "E2", "E3" }; 

and got an error

error: array size "ENames is non-integer type" E

error: too many initializers for 'const char * [1]

Q: why does the enum class become non-integral in C ++ 11, whereas the regular enum is an integral?

What is the solution to the problem? How can I declare an array with a size that is an enum in an enum class ?

Here http://ideone.com/SNHTYe is a simple example.

Thanks.

+6
source share
2 answers

Q: why does the enum class become non-integral in C ++ 11, whereas the regular enum is an integral?

Since this is not a "normal enumeration", it is more strongly typed.

How can I declare an array with a size that is an enum in the enum class?

Why do you want one way or another? You can use static_cast , but the solution to your problem is don't do this.

If you want to enumerate a fixed base type, then do this, do not use an enumerated scope:

 enum E : uint16_t { E1, E2, E3, MaxNum }; const char * ENames[ MaxNum ] = { "E1", "E2", "E3" }; 
+7
source

C ++ 11 5.19 / 3 "Constant Expressions"

An integral constant expression is a literal constant expression of an integral or non-enumerated type .

The copied enumerations are not integral constant expressions. And the size of the array (if specified) should be "an integral constant expression, and its value must be greater than zero" (8.3.4 / 1 "Arrays").

I suspect that this explains why cloud enumerations are implicitly converted to int .

To work around this problem, you can statically translate enobe with scope into int , as suggested by user 2523017, or use pre-C ++ 11 enumeration enumeration methods:

 namespace E { enum { E1, E2, E3, MaxNum }; } 

or

 struct E { enum { E1, E2, E3, MaxNum }; }; 
+5
source

Source: https://habr.com/ru/post/948296/


All Articles