Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 695
Violet Giraffe Avatar asked Mar 01 '19 14:03

Violet Giraffe


1 Answers

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
like image 61
songyuanyao Avatar answered Nov 03 '22 00:11

songyuanyao