Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a strongly-typed enum be initialized with an integer without static_cast?

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?

like image 749
xmllmx Avatar asked Mar 15 '17 09:03

xmllmx


People also ask

What is a strongly typed enum?

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.

Can enum be initialized?

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.

What is an unscoped enum type?

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.

What is an enum in c++?

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.


1 Answers

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

like image 154
UnholySheep Avatar answered Oct 11 '22 19:10

UnholySheep