简体   繁体   中英

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

I'm puzzled. Isn't 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. It does, however, compile without the signed or unsigned keyword.

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.

unsigned char is not a single-word type name, while char is. And this is true for functional cast expression too, that's why ('p') doesn't work either.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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