Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can an initializer-list not be used as an argument?

Tags:

c++

c++11

struct X
{
    int a;
    int b;
};

int f(X x)
{
    return x.a + x.b;
}

int main()
{
    int n = f({1, 2});
}

Visual Studio 2012 (Nov CTP) reports:

error C2664: 'int f(const X &)' : cannot convert parameter 1 from
'initializer-list' to 'X'

Reason: cannot convert from 'initializer-list' to 'X'
Only an initializer-list with zero or one elements can be converted to this type

Build FAILED.
like image 267
xmllmx Avatar asked Oct 21 '22 21:10

xmllmx


2 Answers

Visual Studio 2012 (Nov CTP) reports:

It's not even a beta compiler. It's supposed to work. I'd link to your code working on ideaone, but this website won't let be do that.

File a bug report on it.

like image 112
Nicol Bolas Avatar answered Oct 24 '22 18:10

Nicol Bolas


If you want to pass intializer list style syntax to your constructor then you have to pass a std::initializer_list type to your constructor. This type will then construct an array of your types when passed a { } syntax style construct.

like image 43
Tony The Lion Avatar answered Oct 24 '22 18:10

Tony The Lion