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

↘锁芯ラ 提交于 2019-12-10 15:34:54

问题


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.

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14013135/why-can-an-initializer-list-not-be-used-as-an-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!