Converting enum to enum via int in C ++

Is it possible to convert an enum to another enum using int conversion as shown below? It looks like gcc for x64 has no problem with this, but can we expect something different with other compilers and platforms?

What happens when a

equals A_third

and has no equivalent in enum_B

?

enum enum_A {
    A_first = 0,
    A_second,
    A_third
};

enum enum_B {
    B_first = 0,
    B_second
};

enum_A a = A_first;
enum_B b;

b = enum_B(int(a)); 

      

+3


source to share


1 answer


You have to be careful when doing this, because of some edge cases:

From the C ++ 11 standard (§7.2.6):

For an enumeration whose base type is not fixed, the base type is an integral type that can represent all the counter values ​​defined in the enumeration. If an integral type cannot represent all the values ​​of an enumerator, the enumeration is ill-formed. it is implementation-defined which integral type is used as the base type, except that the base type must not be larger than int if the enumerator value cannot be placed into an int or unsigned int.



This means it is possible that enum

more than int

, so the conversion from enum

to int

may fail with undefined results.

With the above, can be converted int

to enum

, resulting in an enumerator value that is enum

not explicitly specified. Informally, you can think of it enum

as an integral type with multiple values ​​explicitly identified using labels.

+3


source







All Articles