是否可以使用初始值设定项列表创建临时结构/类

Is it possible to create temp structs/classes with initializer lists?

本文关键字:创建 列表 结构 可以使 是否      更新时间:2023-10-16

这看起来是一个非常基本的问题,应该有一个明确的谷歌答案,但到目前为止我还没能找到。答案似乎是否定的,但我想确定一下。我的意思是这样的东西:

struct A { int a,b; };
void foo(const A&); // just some function
foo(A{1,2}); // doesn't work, but it was a long shot
foo(A({1,2})); // looks like it could have worked, but it doesn't
foo(A(std::initializer_list<int>({1,2}))); // ugly and doesn't work either anyway

更新:选项2实际上有效(以及一个更简单的foo({1,2})),但仅在vs2013中有效,而在2012中无效。

更新#2:拜托,有必要这么努力地否决它吗?知道它只从vs2013开始工作仍然很有用。

甚至比这更容易。看看统一初始化的力量:

foo({1,2});