I came across some code like the following in one the CppCon 2014 talks that confused the heck out of me. The audience accepted it without comment, so I presume that it's legal:
enum class Foo { Bar };
Foo const v1 = Foo(5);
The question is: why does this compile? I would expect compilation to fail and complain that we can't convert an int to a Foo. The slightly modified line below fails with the expected error:
Foo const v1(5);
Scoped enumeration types have an implicit underlying type of int
, assuming no other underlying type is specified. All possible values of type int
can be represented.
7.2p5:
[...] For a scoped enumeration type, the underlying type is
int
if it is not explicitly specified. In both of these cases, the underlying type is said to be fixed. [...]
7.2p8:
For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. [...]
And any integral value that can be represented by the enumeration can be explicitly converted to that enumeration type, as @Columbo had pointed out in his now-deleted answer:
5.2.9p10:
A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). [...]
Since there is some confusion in the comments about what that means:
enum class Foo { Bar }; Foo const v1 = Foo(5);
is well-defined. Not undefined, not unspecified, not even implementation-defined. The parts of the standard I quote explain that:
Foo
is int
, and that the underlying type is fixed.Foo
are the values of int
.5
is in the range of the enumeration values, the value is unchanged by the conversion.Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments