c++ - 范围枚举 : error: cannot convert ‘int’ to ‘Handle’ in initialization

标签 c++ c++11 gcc language-lawyer

我正在阅读来自 hereScoped enumerations 页面:

enter image description here 所以我决定试一试:

$ cat e.cxx 
#include <cstdint>
enum class Handle : uint32_t { Invalid = 0 };
int main()
{
  Handle h { 42 }; // OK
  return 0;
}
$ g++ -std=c++11 e.cxx
e.cxx: In function ‘int main()’:
e.cxx:5:17: error: cannot convert ‘int’ to ‘Handle’ in initialization
   Handle h { 42 }; // OK

             ^

使用:

$ g++ --version
g++ (Debian 5.3.1-14) 5.3.1 20160409
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

如果我现在检查 GCC 中的 C++11 支持,似乎自 GCC 4.8 以来一切都受支持。 .

那么我读错了哪一页? Score enumertions 的示例不是 100% 正确,或者 GCC 对 C++11 的支持仍然不完整?

最佳答案

enum class(或 enum struct)创建一个strong 类型。它不能简单地使用底层整数类型进行初始化,它需要显式转换,至少在 C++11 和 C++14 中是这样。

您显示的引用屏幕截图来自即将发布的 C++17 标准,该标准稍微放宽了要求,并允许这种类型的初始化。

关于c++ - 范围枚举 : error: cannot convert ‘int’ to ‘Handle’ in initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37413895/

相关文章:

c++ - 如何访问 "int20_t"中的数据?

c++ - 正在写入 &str[0] 缓冲区(std :string) well-defined behaviour in C++11?

c++ - 星号不是字符常量?

c - 交换C中多维数组的子数组

c++ - 为什么 GCC 优化掉这个增量?

c++ - 类范围内的二维 vector

c++ - 如何解析以下文件

c++ - basic_string::_M_construct null 在构造字符串的子 vector 后无效

c++ - 在 recvfrom 系统调用期间取消 C++11 std::thread?

c++ - 什么是 sqlite 的好的 OO C++ 包装器