简体   繁体   English

C ++ 11初始化语法问题(使用gcc 4.5 / 4.6)

[英]C++11 initialization syntax issue (with gcc 4.5 / 4.6)

What is wrong with the following C++11 code: 以下C ++ 11代码有什么问题:

struct S
{
    int a;
    float b;
};

struct T
{
    T(S s) {}
};

int main()
{
    T t(S{1, 0.1});  // ERROR HERE
}

gcc gives an error at the indicated line (I tried both gcc 4.5 and an experimental build of gcc 4.6) gcc在指定的行给出错误(我尝试了gcc 4.5和gcc 4.6的实验版本)

Is this not valid C++11, or is gcc's implementation incomplete? 这不是有效的C ++ 11,还是gcc的实现不完整?

EDIT: Here are the compiler errors: 编辑:这是编译器错误:

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

According to proposal N2640 , your code ought to work; 根据提案N2640 ,你的代码应该工作; a temporary S object should be created. 应该创建一个临时S对象。 g++ apparently tries to parse this statement as a declaration (of a function t expecting S), so it looks like a bug to me. g ++显然试图将这个语句解析为一个声明(函数t期待S),所以它看起来像是一个bug。

It seems wrong to call a constructor without parentheses, and this seems to work: 调用没有括号的构造函数似乎是错误的,这似乎有效:

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.
}

It would seem logical (at least to me :s ) that your example doesn't work. 这似乎是合乎逻辑的(至少对我来说:s ),你的例子不工作。 Replacing S with a vector<int> gives the same result. 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})); // does

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

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