为什么"自动ch = unsigned char {'p'}"在C++ 17下编译?

Vio*_*ffe 35 c++ language-lawyer c++14 c++17

我很困惑.不是const auto ch = unsigned char{'p'};一个完全有效的初始化表达式?所有三个主要编译器都无法使用几乎相同的错误消息进行编译:

错误:预期'('用于函数式转换或类型构造

交换花括号('p')没有任何变化.但是,它确实在没有signedor unsigned关键字的情况下编译.

在线演示.

son*_*yao 42

因为只有单字类型名称可以用于这种显式类型转换.

单字类型名称后跟braced-init-list是指定类型的prvalue,使用指定的braced-init-list进行designating a temporary (until C++17) whose result object is (since C++17)direct-list-initialized.

unsigned char不是单字类型名称,char而是.对于功能性演员表达也是如此,这也是为什么('p')不起作用的原因.

作为解决方法,你可以

using uc = unsigned char;  // or use typedef
const auto ch = uc{'p'};
Run Code Online (Sandbox Code Playgroud)

或者将其更改为其他演员风格.

const auto ch = (unsigned char) 'p';  // c-style cast expression
const auto ch = static_cast<unsigned char>('p');  // static_cast conversion
Run Code Online (Sandbox Code Playgroud)

  • 你碰巧知道这个限制的原因吗?就像,如果允许多字类型名称,那么其他什么东西会被打破? (5认同)
  • C风格演员,真的吗?那么`static_cast`怎么样(或者在使用Boost的情况下,`boost :: implicit_cast`)?该语言允许[*simple-type-specifier*](https://timsong-cpp.github.io/cppwp/n4659/dcl.type.simple#nt:simple-type-specifier)或(在模板中)一个[*typename-specifier*](https://timsong-cpp.github.io/cppwp/n4659/temp.res#nt:typename-specifier),BTW,在函数式演员表中,确切地说.你的声明"它不能有空格"有点误导,因为例如`std :: uint8_t`有空格并且是一个有效的*simple-type-specifier*. (4认同)
  • @VioletGiraffe因为`uc {'p'}`/`uc('p')`是一个功能演员.函数名称中不能包含空格,因此类型名称也不能. (2认同)