问题描述
请考虑以下代码段:
#include <iostream>
struct A {
A() {}
A(const A&) {}
};
struct B {
B(const A&) {}
};
void f(const A&) { std::cout << "A" << std::endl; }
void f(const B&) { std::cout << "B" << std::endl; }
int main() {
A a;
f( {a} ); // A
f( {{a}} ); // ambiguous
f( {{{a}}} ); // B
f({{{{a}}}}); // no matching function
}
为什么每个调用都构造相应的输出?大括号的数量如何影响统一初始化?括号删除如何影响所有这些?
Why does each call fabricate the corresponding output? How does the number of braces affect uniform initialization? And how does brace elision affect all this?
推荐答案
过载分辨率很有趣.
-
{a}
具有完全匹配等级,用于初始化(临时)const A&
参数,该参数胜过用户定义的转换B(const A&)
作为{a}
的实现. 在C ++ 14中添加了此规则,以解决列表初始化中的歧义(以及对聚合的调整).
{a}
has exact match rank for initializing (a temporary for) theconst A&
parameter, which outcompetes the user-defined conversionB(const A&)
as a realization of{a}
. This rule was added in C++14 to resolve ambiguities in list-initialization (along with adjustments for aggregates).
请注意,名义临时名称是从未创建:在重载解析选择f(const A&)
之后,引用只是初始化为引用a
,并且此解释甚至可以应用于不可复制的类型.
Note that the notional temporary is never created: after overload resolution picks f(const A&)
, the reference is simply initialized to refer to a
, and this interpretation can apply even for non-copyable types.
不涉及括号删除-我们不知道允许使用的最外面的目标类型.
No brace elision is involved—we don’t know the outermost target type to allow it.
这篇关于大括号的数量如何影响统一初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!