简体   繁体   English

为什么强类型枚举可以用没有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'
}

My compiler is clang 4.0 with option -std=c++1z . 我的编译器是clang 4.0 ,选项为-std=c++1z

It is expected that E e2 = 0; 预计E e2 = 0; is not ok, because E is strongly-typed. 不好,因为E是强类型的。 However, what surprised me is that E e1{ 0 }; 然而,让我感到惊讶的是E e1{ 0 }; should be ok. 应该可以。

Why can a strongly-typed enum be initialized with an integer without static_cast ? 为什么强类型枚举可以用没有static_cast的整数初始化?

Looking at the reference using list intializers is allowed since C++17: 从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 ) 自3.9版以来,Clang支持此功能(根据实施状态页面

GCC supports this since version 7 (according to the standards support page ) GCC从版本7开始支持此功能(根据标准支持页面

See this C++ proposal for additional context and motivation: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0138r2.pdf 有关其他背景和动机,请参阅此C ++提案: http//www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0138r2.pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM