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

822 Views Asked by At

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

Is this not valid C++11, or is gcc's 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
2

There are 2 best solutions below

0
On BEST ANSWER

According to proposal N2640, your code ought to work; a temporary S object should be created. g++ apparently tries to parse this statement as a declaration (of a function t expecting S), so it looks like a bug to me.

3
On

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