c++ - I(I()) 的含义

标签 c++ language-lawyer most-vexing-parse

示例代码:

typedef int I;
struct X{ X(int); };

int main()
{
    int(int());
    X(X());
    I(I());
}

int(int()); 行是一个使用函数式转换表示法的表达式 - 它是一个临时的 int,用值初始化的 int

X(X()); 是一个名为 X 的函数的声明,该函数不带任何参数返回结构 X

我的问题是:这里的I(I())是什么意思?标准中的哪些规则决定了这三种情况之间的含义差异?

最佳答案

该规则表示,如果构造对于声明或语句的语法有歧义,则将其视为声明。

[stmt.ambig] 1 There is an ambiguity in the grammar involving expression-statements and declarations: An expression- statement with a function-style explicit type conversion (5.2.3) as its leftmost subexpression can be indis- tinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration.

X(X()); 是有歧义的,因为它既可以是强制转换,也可以是函数声明,所以它被认为是声明。

int(int()); 不能是函数声明,因为作为关键字的 int 不是函数的有效名称。所以,没有歧义,就是类型转换。

同样,I(I()); 不能是函数声明,因为虽然不是关键字,I 也不是有效名称,因为它会重新声明键入 I 作为函数,这是不允许的,因此它是一个转换。

关于c++ - I(I()) 的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45496423/

相关文章:

c++ - 奇怪的opengl渲染口吃

c++ - 使用 C 而不是 C++ 编译头文件

C++ 并将枚举值写入 Windows 注册表

c++ - reinterpret_cast 可以更改对象表示吗?

c++ - 最烦人的解析

c++ - 如何使用可变模板参数调用模板函数?

c++ - 为什么逗号运算符在运算符 [] 中被调用,而不是在运算符 () 中?

c++ - 转换为不相关的引用类型是否违反了严格的别名规则?

c++ - 为什么我的构造函数允许使用临时对象调用非 const 引用作为参数?

c++ - 带空括号的默认构造函数