C ++ 11 initialization syntax (with gcc 4.5 / 4.6)

What is wrong with the following C ++ 11 code:

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 on the specified line (I tried both gcc 4.5 and the experimental build of gcc 4.6)

Is this invalid C ++ 11 or is the gcc implementation incomplete?

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 
+4
source share
2 answers

According to proposal N2640 , your code should work; you need to create a temporary object S. g ++ is clearly trying to parse this operator as an declaration (of a function t waiting for S), so it looks like an error to me.

+3
source

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 for me :s ) that your example is not working. Replacing S with a vector<int> gives the same result.

 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 
0
source

Source: https://habr.com/ru/post/1334026/


All Articles