为什么强类型枚举可以用不带static_cast的整数初始化?

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'
}

我的编译器是 clang 4.0,带有选项 -std=c++1z

预计E e2 = 0;是不行的,因为E是强类型的。不过,让我意外的是E e1{ 0 };应该没问题。

为什么强类型枚举不用static_cast就可以用整数初始化?

查看 reference 自 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 从 3.9 版开始支持这个(根据 implementation status page

GCC 自版本 7 起支持此功能(根据 standards support page

查看此 C++ 提案以获得更多背景信息和动机:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0138r2.pdf