简体   繁体   English

为什么“ auto ch = unsigned char {'p'}”不能在C ++ 17下编译?

[英]Why doesn't “auto ch = unsigned char{'p'}” compile under C++ 17?

I'm puzzled. 我很困惑 Isn't const auto ch = unsigned char{'p'}; const auto ch = unsigned char{'p'};不是const auto ch = unsigned char{'p'}; a perfectly valid initialization expression? 一个完全有效的初始化表达式? Fails to be compiled by all three major compilers with almost identical error messages: 无法由所有三个主要的编译器进行编译,并显示几乎相同的错误消息:

error: expected '(' for function-style cast or type construction 错误:对于函数样式强制转换或类型构造,应为'('

Swapping curly braces for ('p') changes nothing. 将花括号换成('p')不会改变任何内容。 It does, however, compile without the signed or unsigned keyword. 但是,它可以在没有signed或未unsigned关键字的情况下进行编译。

Online demo. 在线演示。

Because only single-word type name could be used for this kind of 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. 单字类型名称后跟一个括号初始列表,是指定类型的prvalue,它指定designating a temporary (until C++17) whose result object is (since C++17)直接用指定的列表进行初始化括号初始化列表。

unsigned char is not a single-word type name, while char is. unsigned char不是单字类型名称,而char是。 And this is true for functional cast expression too, that's why ('p') doesn't work either. 而且对于函数强制转换表达式也是如此,这就是为什么('p')也不起作用。

As the workaround, you can 解决方法是,您可以

using uc = unsigned char;  // or use typedef
const auto ch = uc{'p'};

Or change it to other cast styles. 或将其更改为其他演员样式。

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

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

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