下面的C++11代码有什么问题:
struct S
{
int a;
float b;
};
struct T
{
T(S s) {}
};
int main()
{
T t(S{1, 0.1}); // ERROR HERE
}gcc在标示的行上给出了一个错误(我尝试了gcc 4.5和gcc 4.6的实验版本)
这是无效的C++11,还是gcc的实现不完整?
编辑:以下是编译器错误:
test.cpp: In function int main():
test.cpp:14:10: error: expected ) before { token
test.cpp:14:10: error: a function-definition is not allowed here before { token
test.cpp:14:18: error: expected primary-expression before ) token
test.cpp:14:18: error: expected ; before ) token发布于 2011-01-03 11:22:07
根据proposal N2640,您的代码应该可以工作;应该创建一个临时S对象。显然,g++试图将此语句解析为声明(函数t期望S),因此在我看来它就像是一个bug。
发布于 2011-01-03 17:56:53
调用不带括号的构造函数似乎是错误的,这似乎是有效的:
struct S
{
int a;
float b;
};
struct T
{
T(S s) {}
};
int main()
{
T t(S({1, 0.1})); // NO ERROR HERE, due to nice constructor parentheses
T a({1,0.1}); // note that this works, as per link of Martin.
}你的例子不起作用似乎是合乎逻辑的(至少对我:s来说是这样)。用vector<int>替换S会得到相同的结果。
vector<int> v{0,1,3}; // works
T t(vector<int>{0,1,2}); // does not, but
T t(vector<int>({0,1,2})); // doeshttps://stackoverflow.com/questions/4581817
复制相似问题