Why does the number of elements in a initializer list cause an ambiguous call error?

前端 未结 3 1842
野性不改
野性不改 2020-12-29 18:02

Why are the first two calls to doSomething OK by the compiler, but using two elements in the list causes an ambiguous call?

#include 

        
3条回答
  •  长情又很酷
    2020-12-29 18:28

    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 is conflicting with the iterator range constructor of std::vector.

    If we change the code to instead be

    doSomething({"hello"s, "stack"s});
    

    Then the elements of the initializer list are now std::strings so there is no ambiguity.

提交回复
热议问题