enum class E
{};
int main()
{
E e1{ 0 }; // ok
E e2 = 0; // not ok
// error : cannot initialize a variable of
// type 'E' with an rvalue of type 'int'
}
My compiler is clang 4.0
with option -std=c++1z
.
It is expected that E e2 = 0;
is not ok, because E
is strongly-typed. However, what surprised me is that E e1{ 0 };
should be ok.
Why can a strongly-typed enum be initialized with an integer without static_cast
?
Strongly-typed enumerationsThe enumerators can only be accessed in the scope of the enumeration. The enumerators don't implicitly convert to int. The enumerators aren't imported in the enclosing scope. The type of the enumerators is by default int. Therefore, you can forward the enumeration.
There are rules about initializing enums. You need to know them. This question investigates the initialization of enums, which are a data type that allows for a variable to be a set of predefined constants; the variable must be equal to one of the defined constants.
In an unscoped enum, the scope is the surrounding scope; in a scoped enum, the scope is the enum-list itself. In a scoped enum, the list may be empty, which in effect defines a new integral type. By using this keyword in the declaration, you specify the enum is scoped, and an identifier must be provided.
Enum, which is also known as enumeration, is a user-defined data type that enables you to create a new data type that has a fixed range of possible values, and the variable can select one value from the set of values.
Looking at the reference using list intializers is allowed since C++17:
Both scoped enumeration types and unscoped enumeration types whose underlying type is fixed can be initialized from an integer without a cast, using list initialization, if all of the following is true:
- the initialization is direct-list-initialization
- the initializer list has only a single element
- the enumeration is either scoped or unscoped with underlying type fixed
- the conversion is non-narrowing
Clang supports this since version 3.9 (according to the implementation status page)
GCC supports this since version 7 (according to the standards support page)
See this C++ proposal for additional context and motivation: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0138r2.pdf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With