initializer_list和默认构造函数重载解析 [英] initializer_list and default constructor overload resolution
问题描述
#include <initializer_list>
#include <iostream>
using namespace std;
struct Y {};
struct X
{
X(initializer_list<Y>) { cout << "yay" << endl; }
explicit X() { cout << "boo" << endl; }
};
X f()
{
return {};
}
int main()
{
f();
return 0;
}
这将打印出 boo。为什么它不打印出是?
This prints out "boo". Why doesn't it print out "yay" ?
总有办法区分以下两种构造:
Is there anyway to differentiate the following two constructions:
-
X()
-
X {}
X()
X{}
或
-
return X();
-
return {};
return X();
return {};
或
void g(const X&)
-
g(X())
-
g({})
g(X())
g({})
谢谢。
推荐答案
总有办法区分以下两种结构:
Is there anyway to differentiate the following two constructions:
否。它们不是不同的构造。
No. They are not different constructs.
{}构造器语法的主要目的是引入 uniform 初始化,以使初始化工作在所有地方都相同。如果它们之间存在差异,那将不是统一的。
The primary purpose of the {} constructor syntax was to introduce uniform initialization, to have initialization work the same everywhere. If there was a difference between them, it wouldn't be uniform.
如果要使用空的初始值设定项列表构造函数,则必须声明要传递显式的初始化列表。像这样: return initializer_list< Y> {};
当然,统一初始化的另一目的是不必键入太多类型名,因此您可以实现与 return {{}};
If you want to use the empty initializer list constructor, you have to state that you're passing an initializer list explicitly. Like this: return initializer_list<Y>{};
Of course, one of the other purposes of uniform initialization is to not have to type out typenames so much, so you can achieve the same effect with return {{}};
这篇关于initializer_list和默认构造函数重载解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!