简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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