Artificial Mind Artificial Mind - 15 days ago 7
C++ Question

Why does unsigned int not work in constructor syntax?

So this question might be a little odd, but why is the following illegal in C++?

auto x = unsigned int(0);


Whereas the following are all ok:

auto y = int(0);
auto z = unsigned(0);
auto w = float(0);


or in general

auto t = Type(... c-tor-args ...);


(with the exception of
Type
being
unsigned int
)

Answer

This is explicit type conversion, and functional cast expression consists of a single-word type specifier is not valid.

(emphasis mine)

The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name: unsigned int(expression) or int*(expression) are not valid), followed by a single expression in parentheses. This cast expression is exactly equivalent to the corresponding C-style cast expression.

You can change it to c-style cast expression or static_cast:

auto x1 = (unsigned int)(0);
auto x2 = static_cast<unsigned int>(0);