前几天有人问为什么有些东西可以用clang编译,但不能用gcc编译。我直观地理解正在发生的事情并能够帮助这个人,但这让我想知道——根据标准,哪个编译器是正确的?这是代码的简化版本:
#include <iostream>
#include <string>
class foo
{
public:
foo(const std::string& x):
name(x)
{ }
foo& operator()(const std::string& x)
{
std::cout << name << ": " << x << std::endl;
return (*this);
}
std::string name;
};
int main()
{
std::string x = "foo";
foo(x)("bar")("baz");
return 0;
}
这与 clang++ 编译得很好,但 g++ 给出了以下错误:
runme.cpp: In function ‘int main()’:
runme.cpp:21:11: error: conflicting declaration ‘foo x’
foo(x)("bar")("baz");
^
runme.cpp:20:17: error: ‘x’ has a previous declaration as ‘std::string x’
std::string x = "foo";
如果我在第 21 行添加一对括号,g++ 很高兴:
(foo(x))("bar")("baz");
换句话说,g++ 将此行解释为:
foo x ("bar")("baz");
我认为它是 g++ 中的错误,但我又想问标准专家,哪个编译器出错了?
PS:gcc-4.8.3、clang-3.5.1