Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 405
Artificial Mind Avatar asked Nov 23 '16 12:11

Artificial Mind


People also ask

Should a struct have a constructor?

Technically, a struct is like a class , so technically a struct would naturally benefit from having constructors and methods, like a class does.

Can AC struct have a constructor?

3. Constructor creation in structure: Structures in C cannot have a constructor inside a structure but Structures in C++ can have Constructor creation.

Do structures have constructors and destructors?

In C++, we can declare/define the structure just like class and have the constructors/destructors for the Structures and have variables/functions defined in it. The only difference is the default scope of the variables/functions defined.


1 Answers

The syntax is Explicit type conversion (functional notation) here. According to the grammatical rule, it only works with simple type specifier or typedef specifier (i.e. a single-word type name).

(emphasis mine)

2) 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 typedef specifier as @Jean-FrançoisFabre suggested.

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

Quotes from the standard, $5.2.3/1 Explicit type conversion (functional notation) [expr.type.conv]

A simple-type-specifier ([dcl.type.simple]) or typename-specifier ([temp.res]) followed by a parenthesized optional expression-list or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer.

And $7.1.7.2/1 Simple type specifiers [dcl.type.simple]

The simple type specifiers are

simple-type-specifier:     nested-name-specifieropt type-name     nested-name-specifier template simple-template-id     nested-name-specifieropt template-name     char     char16_t     char32_t     wchar_t     bool     short     int     long     signed     unsigned     float     double     void     auto     decltype-specifier type-name:     class-name     enum-name     typedef-name     simple-template-id decltype-specifier:   decltype ( expression )   decltype ( auto ) 
like image 77
songyuanyao Avatar answered Sep 23 '22 07:09

songyuanyao