简体   繁体   English

使用额外括号时“错误:预期表达式”

[英]“error: expected expression” when using extra parentheses

I just stumbled across a compiler error that I was not expecting: 我偶然发现了一个我没想到的编译器错误:

std::cout << sizeof(int)   << std::endl;  // ---> this is valid (obviously)
std::cout << sizeof((int)) << std::endl;  // ---> this leads to
                                          // "error: expected expression"

Similarly, we have: 同样,我们有:

template <typename T>
struct Foo
{
    T value;
};
Foo<int>   f1;  // ---> this is valid (obviously)
Foo<(int)> f2;  // ---> this leads to "error: expected expression"

Apparently, the compiler interprets (T) as an explicit conversion and stops there. 显然,编译器将(T)解释为显式转换并在那里停止。 I understand the error, I understand what the compiler is expecting, what I do not get is why (T) cannot be treated as T if it is not in the context of (T)(exp) . 我理解错误,我理解编译器期望什么,我不知道的是为什么(T)不能被视为T如果它不在(T)(exp)的上下文中。 I thought that the compiler would be able to see through that (and probably return a warning), so I suppose this means that there are ambiguous cases where allowing those extra parentheses would lead to errors. 我认为编译器能够看透(并且可能会返回警告),所以我认为这意味着存在不明确的情况,允许那些额外的括号会导致错误。

My questions are: when would that be dangerous? 我的问题是:什么时候会有危险? Is that in the C++ standard? 这是C ++标准吗?

This was tested with clang 3.3. 这是用clang 3.3测试的。 and g++ 4.7.2. 和g ++ 4.7.2。

sizeof expects either a value (an expression) or a type. sizeof (表达式)或类型。 (int) is neither one of them - you can't treat types as values and expect them to act correctly in cases where you would expect values to do so, because they are not (first-class) values. (int)既不是其中之一 - 你不能将类型视为值,并期望它们在你期望值这样做的情况下正确行动,因为它们不是(一等)值。 Therefore, you can't just parenthesize a type and have the same type come out. 因此,您不能只是将类型括起来并使类型相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM