编译器如何确定vector与initializer_list之间的关系? [英] How does the compiler decide between vector vs initializer_list?

查看:70
本文介绍了编译器如何确定vector与initializer_list之间的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,使用两种版本的print方法,第一个调用将解析为带有initializer_list的调用。如果我用initializer_list注释掉定义,则程序将无缝使用矢量版本。在第一种情况下,我希望编译器会抱怨!

In the code below, with both versions of the print method present the first call resolves to the one with initializer_list. If I comment out the definition with initializer_list, the program seamlessly uses the vector version. In the first case I was expecting the compiler to complain!

#include <iostream>
#include <vector>
using namespace std;

void print(const vector<int>& v1){
        cout << "vector \n";
}
void print(const initializer_list<int>& il) {
         cout << "init list \n";
}

int main() {
        print({1,2,3,4,5});
        return 0;
}


推荐答案

这是过载分辨率在C ++中有效。两种版本的 print 均可用于重载解析。

This is how overload resolution works in C++. Both versions of print are viable for overload resolution.


  • print(const vector< int& v1)是用于重载解析的可行函数,因为输入初始值设定项列表 {1,2,3,4,5} 可隐式转换为 std :: vector< int>

  • print(const initializer_list< int>& il)是用于重载解析的可行函数,因为调用方中的输入类型完全匹配。

  • print(const vector<int>& v1) is a viable function for overload resolution because input initializer list {1,2,3,4,5} in the caller is implicitly convertible to a std::vector<int>.
  • print(const initializer_list<int>& il) is a viable function for overload resolution cause the input type in the caller perfectly matches.

当两个重载都起作用时, print(const initializer_list< int>& il)被选为最佳可行函数,因为它是完美匹配并且完美匹配在重载解析中的优先级高于隐式转换。

When both overloads are into play print(const initializer_list<int>& il) is chosen as the best viable function cause it's a perfect match and a perfect match has a higher priority in overload resolution than an implicit conversion.

这篇关于编译器如何确定vector与initializer_list之间的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆