Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ enum class integer not working for array subscript

Tags:

c++

c++11

I have the following enum class:

enum class EnumClass : int
{
    A = 0, B
};

Now I want to subscript with that enum type to an array:

MyObject arr[2];
.
.
.
MyObject a = arr[EnumClass::A]
MyObject b = arr[EnumClass::B]

Unfortunately I get the following error message:

array subscript is not an integer

As enum classes are strongly typed I would expect this to work.

like image 510
Objective Avatar asked Jul 07 '14 15:07

Objective


People also ask

What number do C enums start at?

If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on.

Can enum start with number C++?

So yes, if you do not specify a start value, it will default to 0.

How do you change the size of an enum?

The size of an enum is compiler-specific and should default to the smallest integral type which is large enough to fit all of the values, but not larger than int. In this case, it seems the sizeof enum is fixed at 16-bit.

How do you assign a value to an enum in C++?

By default, the starting code value of the first element of enum is 0 (as in the case of array) . But it can be changed explicitly. For example: enum enumerated-type-name{value1=1, value2, value3}; And, The consecutive values of the enum will have the next set of code value(s).


1 Answers

As enum classes are strongly typed I would expect this to work

On the contrary, that's exactly why it won't work. Scoped enumerations will not implicitly convert to the underlying type. Use static_cast instead.

MyObject a = arr[static_cast<int>(EnumClass::A)];
like image 167
Praetorian Avatar answered Sep 21 '22 02:09

Praetorian