c++ - 花括号初始化列表和无符号类型

标签 c++ initialization c++14 language-lawyer

gcc 8 和 clang 7 不接受下面的代码,它应该默认构造一个 unsigned int 类型的临时文件:

unsigned int ui = unsigned int{};

clang 7报错如

<source>:6:22: error: expected primary-expression before 'unsigned'

Visual C++ 2015 和 2017 接受这一点。

显然,这适用于 int 或任何可默认构造的类类型。

这是正确的 C++14 代码吗(在那种情况下是 clang 和 gcc 的错误)?如果不是,为什么不呢?除无符号类型外,哪些类型会受到相同的限制?

最佳答案

new_type { expression-list(optional) } like unsigned int{} 符合 explicit type conversion 的语法, 只允许单字类型名称。

A single-word type name followed by a braced-init-list is a prvalue of the specified type designating a temporary (until C++17) whose result object is (since C++17) direct-list-initialized with the specified braced-init-list.

请注意,unsigned int 不是单字类型名称,而 int 是。所以 int {} 工作正常。

这对于函数式转换表达式也是一样的,

The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name: unsigned int(expression) or int*(expression) are not valid),

作为解决方法,您可以应用类型别名,例如

using type = unsigned int;
type ui = type{};

关于c++ - 花括号初始化列表和无符号类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336344/

相关文章:

c++ - 函数模板适用于本地 lambda,但不适用于其他函数

c++ - 字符串字面量引用类

C++ 函数对象参数

python - 子目录结构破坏了 C++ 扩展构建

php - 在 PHP 中初始化(空)数组的最佳方法

C++ 调用 Struct 及其继承成员的默认构造函数

reactjs - React Redux 表单初始化

c++ - 为什么在函数中使用多个 getlines 来输入字符串会出现意外行为?

C++ 错误 : expected primary expression before '*' token in constructor with parameters

c++ - Lua-C++ 集成 : Calling function in table from C++