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;
}
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 isconst char[N]
. Nowstd::vector
has a constructor that takes two iterators which the pointers qualify for. Because of that theinitializer_list
constructor of thestd::vector<std::string>
is conflicting with the iterator range constructor ofstd::vector<int>
.If we change the code to instead be
Then the elements of the initializer list are now
std::string
s so there is no ambiguity.