c++ - 为什么构造函数语法不能与 "unsigned int"类型一起使用?

标签 c++ type-conversion language-lawyer

为什么以下在 C++ 中是非法的?

auto x = unsigned int(0);

而以下都可以:

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

或一般来说:

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

(除了 Typeunsigned int)。

最佳答案

语法是Explicit type conversion (functional notation)这里。根据语法规则,它只适用于简单类型说明符或 typedef 说明符(即单字类型名称)。

(强调我的)

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.

您可以将其更改为 c 风格的强制转换表达式或 static_cast,或者按照@Jean-FrançoisFabre 的建议将其与 typedef 说明符一起使用。

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

引用标准,$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.

还有 $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 )

关于c++ - 为什么构造函数语法不能与 "unsigned int"类型一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765232/

相关文章:

c++ - 计算两个描述符之间的距离

c++ - 模板参数中的T&和T&&有什么区别?

java - 在java中通过实例名称作为字符串调用实例方法

c++ - 为什么 “cast from ‘X*’ 到 ‘Y’ 失去精度”是一个硬错误,什么是遗留代码的合适修复

C++ 构造函数问题

java - String int 变量说明

r - 如何使用 dplyr 和 magrittr 将数据操作传递到需要数值向量的函数中?

c++ - 聚合类型是否意味着它也是标准布局?

c++ - 模板化构造函数中模板参数的数量

c++ - 使用 INF 文件 c++ 以编程方式安装驱动程序