调用重载<大括号括起来的初始值设定项列表>是模棱两可的,如何处理?

call of overloaded <brace-enclosed initializer list> is ambiguous, how to deal with that?

本文关键字:gt 模棱两可 何处理 处理 列表 lt 重载 起来 调用      更新时间:2023-10-16

我真的不明白这一点,我认为编译器首先执行大括号中的内容,然后将结果提供给最合适的函数。在这里,它看起来像是给函数一个初始值设定项列表来处理它......

#include <string>
#include <vector>
using namespace std;
void func(vector<string> v) { }
void func(vector<wstring> v) { }
int main() {
  func({"apple", "banana"});
}

错误:

<stdin>: In function 'int main()':
<stdin>:11:27: error: call of overloaded 'func(<brace-enclosed initializer list>)' is ambiguous
<stdin>:11:27: note: candidates are:
<stdin>:6:6: note: void func(std::vector<std::basic_string<char> >)
<stdin>:8:6: note: void func(std::vector<std::basic_string<wchar_t> >)

为什么我的func(vector<string> v)过载不被调用,我可以这样做吗?

这个很微妙。

std::vector有一个构造函数,采用两个范围迭代器。它是一个模板构造函数(在 C++11 标准的 23.6.6.2 中定义):

template<typename InputIterator>
vector(InputIterator first, InputIterator last, 
const allocator_type& a = allocator_type());

现在,std::vector<wstring>接受initializer_list的构造器与函数调用中的隐式转换不匹配(const char*string是不同的类型);但是上面的那个,当然包含在std::vector<string>std::vector<wstring>中,是一个潜在的完美匹配,因为InputIterator可以推断为const char*。除非使用某种 SFINAE 技术来检查推导的模板参数是否确实满足向量底层类型的InputIterator概念(这不是我们的情况),否则此构造函数是可行的。

但话又说回来,std::vector<string>std::vector<wstring> 都有一个可行的构造函数,它实现了从支撑初始值设定项列表的转换:因此,歧义。

所以问题在于,尽管"apple""banana"并不是真正的迭代器(*),但它们最终被视为迭代器。向函数调用添加一个参数"joe"通过消除调用的歧义来解决问题,因为这会强制编译器排除基于范围的构造函数并选择唯一可行的转换(initializer_list<wstring>是不可行的,因为const char*不能转换为wstring)。


*实际上,它们是指向const char的指针,因此它们甚至可以被视为字符的常量迭代器,但绝对不是字符串,因为我们的模板构造函数愿意考虑。