函数调用中的单元素矢量初始化 [英] Single-Element-Vector Initialization in a Function Call
问题描述
请考虑以下示例代码:
示例:
void print(int n) {
cout << "element print\n";
}
void print(vector<int> vec) {
cout << "vector print\n";
}
int main() {
/* call 1 */ print(2);
/* call 2 */ print({2});
std::vector<int> v = {2};
/* call 3 */ print(v);
/* call 4 */ print( std::vector<int>{2} );
return 0;
}
会产生以下输出:
element print
element print
vector print
vector print
为什么对 print
函数的调用(在上面的示例中为调用2)与接受单个值的函数匹配?我要在此调用中创建一个向量(包含单个元素),所以调用以向量为输入的 print
匹配它是否不匹配?
Why the call to print
function (call 2 in above example) is getting matched to function accepting a single value? I am creating a vector (containing a single element) in this call, so should it not match to call to print
with vector as input?
在另一个问题中进行了部分讨论所提供的解决方案适用于具有1个以上元素的向量。
This is partially discussed in an other question where the provided solution works for vectors with more than 1 elements.
推荐答案
因为第一重载在 print({2});
。
在两种情况下复制列表初始化适用于第一次超载,其中 int
,
In both cases copy list initialization applies, for the 1st overload taking int
,
(强调我的)
否则(如果
T
不是类类型),如果braced-init-list仅包含一个元素,并且T
不是引用类型,或者是与该类型兼容的引用类型e的注意,T
是直接初始化的(在direct-list初始化中)或副本初始化的(在copy-list初始化中),但不允许缩小转换。 / p>
Otherwise (if
T
is not a class type), if the braced-init-list has only one element and eitherT
isn't a reference type or is a reference type that is compatible with the type of the element,T
is direct-initialized (in direct-list-initialization) or copy-initialized (in copy-list-initialization), except that narrowing conversions are not allowed.
{2}
只有一个元素,可用于初始化 int
作为直接参数;
{2}
has only one element, it could be used to initialize an int
as the argument directly; this is an exact match.
对于第二次重载,使用 std :: vector< int>
,
For the 2nd overload taking std::vector<int>
,
否则,将分两个阶段考虑
T
的构造函数:
- 检查所有将
std :: initializer_list
作为唯一参数,或将第一个参数(如果其余参数具有默认值)作为第一个参数的构造函数,并通过针对类型std :: initializer_list
- All constructors that take
std::initializer_list
as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of typestd::initializer_list
这意味着构造一个 std :: initializer_list< int>
并将其用作 std :: vector< int> $的构造函数参数c $ c>(为
print
构造自变量)。需要进行一次用户定义的转换(通过 std :: vector
的构造函数获取一个 std :: initializer_list
),那么匹配比第一个过载更糟糕。
That means an std::initializer_list<int>
is constructed and used as the constructor's argument of std::vector<int>
(to construct the argument for print
). One user-defined conversion (via the constructor of std::vector
taking one std::initializer_list
) is required, then it's worse match than the 1st overload.
这篇关于函数调用中的单元素矢量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!