gpt4 book ai didi

c++ - 是类型(::x);有效的?

转载 作者:IT老高 更新时间:2023-10-28 21:40:35 26 4
gpt4 key购买 nike

discussing Type(identifier); 语法以及它是如何声明的,我遇到了 Type(::x); 不适用于 Clang。我希望给定一个全局变量 x,它会将 ::x 视为一个表达式(::x + 2 有效)并强制转换::xType。但是,它给出了编译器错误。

这里是 a short example :

int x;

int main() {
int(::x); //does not compile
int(::x + 2); //compiles
}

Clang 3.5给出的编译器错误是:

error: definition or redeclaration of 'x' cannot name the global scope

但是,GCC 4.9.0 可以很好地编译它。此代码是否有效?

最佳答案

据我所知,draft C++ standard 涵盖了这一点。栏目8.3 声明符的含义6段说(强调我的前进):

In a declaration T D where D has the form

( D1 )

the type of the contained declarator-id is the same as that of the contained declarator-id in the declaration

T D1

Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

所以:

int(::x);

相当于:

int ::x ;

这显然是无效的,这也会产生相同的错误。所以gcc 4.9这里不正确,但因为这在 gcc 4.8.3 中看起来是固定的稍后发布我希望这将在 4.9 的后续版本中得到修复也是。虽然我在 gcc 4.8.3 bugs fixed list 中没有看到任何明显的匹配问题但他们并没有声称这是一个完整的列表。

第二种情况是函数显式类型转换,在 5.2.3 部分中有介绍。 显式类型转换(函数式表示法) 表示:

A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).[...]

这是明确的,因为 ::x + 2是一个表达式

涵盖何时将语句视为声明或表达式的部分是6.8 歧义解决说:

There is an ambiguity in the grammar involving expression-statements and declarations: An expressionstatement with a function-style explicit type conversion (5.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is a declaration. [ Note: To disambiguate, the whole statement might have to be examined to determine if it is an expression-statement or a declaration. This disambiguates many examples.

并提供以下示例:

T(a)->m = 7; // expression-statement
T(a)++; // expression-statement
T(a,5)<<c; // expression-statement
T(*d)(int); // declaration
T(e)[5]; // declaration
T(f) = { 1, 2 }; // declaration
T(*g)(double(3)); // declaration

注意:没有 ()然后 T ::DT 的情况下是 qualified-id是一个,它被5.1 的语法所涵盖基本表达式

更新

提交了 gcc bug report .

gcc 的回应是:

Current G++ and EDG both treat it as the valid expression (int)::x

由于此响应暗示 clang不正确(我不同意),我提交了 clang bug reportolder bug report看起来相似,似乎不同意 gcc回应。

更新 2

响应 clang bug report理查德史密斯同意这应该被视为一种声明,并说:

That does not imply clang is incorrect; in fact, Clang is correct here, as far as I can see. (I've also sent a bug report to EDG.)

That said, we should give a proper 'you hit a vexing parse, here's how to disambiguate' error in this case.

更新 3

gcc confirms这是一个错误。

关于c++ - 是类型(::x);有效的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com