Why initialize temporary enum variables with valid values?

I came across some code like the one below in one of the CppCon 2014 interviews that confused me. The audience accepted this without comment, so I believe this is legal:

enum class Foo { Bar }; Foo const v1 = Foo(5); 

Question: Why is this compiling? I would expect the compilation to fail and report that we cannot convert int to Foo. The slightly modified line below fails with the expected error:

 Foo const v1(5); 
+8
c ++ c ++ 11
source share
1 answer

Numbered enumerated types have an implicit int base type unless another base type is specified. All possible values ​​of type int can be represented.

7.2p5:

[...] For the type of the enumerated enumeration region, the base type is int , if it is not explicitly specified. In both cases, the base type is called fixed. [...]

7.2p8:

For an enumeration whose primary type is fixed, the enumeration values ​​are the values ​​of the base type. [...]

And any integer value that can be represented by an enum can be explicitly converted to this type of enum, as @Columbo pointed out in his now deleted answer:

5.2.9p10:

The value of an integral or enumerated type can be explicitly converted to an enumerated type. The value does not change if the initial value is in the range of the values ​​of enumeration (7.2). [...]

Since the comments say what this means:

 enum class Foo { Bar }; Foo const v1 = Foo(5); 

clearly defined. Not undefined, not undefined, not even defined by the implementation. The parts of the standard that I quote explain that:

  • The main type of Foo is int and that the base type is fixed.
  • Foo values ​​are int values.
  • Since 5 is in the range of enumeration values, the value does not change during conversion.
+9
source share

All Articles