函数调用中的单元素矢量初始化

函数调用中的单元素矢量初始化

本文介绍了函数调用中的单元素矢量初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例代码:

示例:

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?

在另一个问题中适用于第一次超载,其中 int

In both cases copy list initialization applies, for the 1st overload taking int,

(强调我的)

{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>,


  • 检查所有将 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 type std::initializer_list

这意味着构造一个 std :: initializer_list< int> 并将其用作 std :: vector< int> (为 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.

这篇关于函数调用中的单元素矢量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:02