为什么初始化列表中的元素数量会导致模棱两可的调用错误? [英] Why does the number of elements in a initializer list cause an ambiguous call error?
问题描述
为什么编译器前两次调用 doSomething
可以,但是使用列表中的两个元素会导致模棱两可的调用?
Why are the first two calls to doSomething
OK by the compiler, but using two elements in the list causes an ambiguous call?
#include <vector>
#include <string>
void doSomething(const std::vector<std::string>& data) {}
void doSomething(const std::vector<int>& data) {}
int main(int argc, char *argv[])
{
doSomething({"hello"}); // OK
doSomething({"hello", "stack", "overflow"}); // OK
doSomething({"hello", "stack"}); // C2668 'doSomething': ambiguous call
return 0;
}
推荐答案
这是怎么回事在两个元素初始化程序列表中,两个字符串文字都可以隐式转换为 const char *
,因为它们的类型是 const char [N]
。现在 std :: vector
有一个构造函数,该构造函数接受两个迭代器,指针有资格获得这些迭代器。因此, std :: vector< std :: string>
的 initializer_list
构造函数与迭代器范围冲突 std :: vector< int>
的构造函数。
What is happening here is that in the two element initializer list both of the string literals can be implicitly converted to const char*
since their type is const char[N]
. Now std::vector
has a constructor that takes two iterators which the pointers qualify for. Because of that the initializer_list
constructor of the std::vector<std::string>
is conflicting with the iterator range constructor of std::vector<int>
.
如果我们将代码改为
doSomething({"hello"s, "stack"s});
然后,初始化列表的元素现在为 std :: string
s,所以没有歧义。
Then the elements of the initializer list are now std::string
s so there is no ambiguity.
这篇关于为什么初始化列表中的元素数量会导致模棱两可的调用错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!