Search code examples
c++enumsstandardsc++17type-safety

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?


Solution

  • 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