Artificial Mind Artificial Mind - 14 days ago 8
C++ Question

Why can constructor syntax not be used with the "unsigned int" type?

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

The syntax is explicit type conversion here, 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, or use it with typedefs as @Jean-FrançoisFabre answered.

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