括号初始化列表和无符号类型 [英] braced-init-list and unsigned types
问题描述
gcc 8和clang 7不接受以下代码,这些代码应默认构造 unsigned int
类型的临时代码:
gcc 8 and clang 7 do not accept the following code, which should default-construct a temporary of type unsigned int
:
unsigned int ui = unsigned int{};
clang 7报告错误,例如
clang 7 reports an error such as
<source>:6:22: error: expected primary-expression before 'unsigned'
Visual C ++ 2015和2017接受此要求.
Visual C++ 2015 and 2017 accept this.
很明显,这适用于 int
之类的类型或任何默认可构造的类类型.
Obviously, this works with a type such as int
, or any default-constructible class type.
这是正确的C ++ 14代码(在这种情况下是clang和gcc的错误)?如果没有,为什么不呢?除无符号类型外,还有哪些类型会受到相同的限制?
Is this correct C++14 code (and in that case a bug of clang and gcc)? If not, why not? Which types other than unsigned types would suffer from the same restriction?
推荐答案
new_type {expression-list(可选)}
(如 unsigned int {}
)符合<一个href ="https://en.cppreference.com/w/cpp/language/explicit_cast" rel ="noreferrer">显式类型转换,该转换只允许使用单个单词类型名称.
new_type { expression-list(optional) }
like unsigned int{}
fits the syntax of explicit type conversion, which allows only single-word type name.
单字类型名称后跟一个括号初始列表,是指定类型的prvalue.
指定一个临时对象(直到C ++ 17)
其结果对象是(因为C ++ 17)
直接用指定的braced-init-list初始化列表.
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 {}
可以正常工作.
Note that unsigned int
is not a single-word type name, while int
is. So int {}
works fine.
对于功能强制转换表达式,
函数强制转换表达式由一个简单的类型说明符或一个typedef说明符组成(换句话说,一个单词类型名称:
unsigned int(expression)
或int *(expression)
无效),
作为解决方法,您可以应用类型别名,例如
As a workaround, you can apply type alias, e.g.
using type = unsigned int;
type ui = type{};
这篇关于括号初始化列表和无符号类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!