developer tip

이니셜 라이저 목록의 요소 수가 모호한 호출 오류를 일으키는 이유는 무엇입니까?

optionbox 2020. 12. 12. 10:38
반응형

이니셜 라이저 목록의 요소 수가 모호한 호출 오류를 일으키는 이유는 무엇입니까?


doSomething컴파일러 에서 처음 두 번 OK를 호출 하지만 목록의 두 요소를 사용하면 모호한 호출이 발생하는 이유는 무엇입니까?

#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포인터가 자격을 갖춘 두 개의 반복자를 취하는 생성자가 있습니다. 그 때문에의 initializer_list생성자 std::vector<std::string>가의 반복기 범위 생성자와 충돌합니다 std::vector<int>.

대신 코드를 변경하면

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

그러면 이니셜 라이저 목록의 요소가 이제 std::strings이므로 모호함이 없습니다.


1 인수 및 3 인수 목록은 모두 std::vector<std::string>std::initializer_list생성자 와 일치 할 수 있습니다 . 그러나 두 인수 목록은의 생성자 중 하나와 일치합니다 std::vector<int>.

template <class InputIt>
vector(InputIt first, InputIt last, Allocator const &alloc = Allocator());

실제로 a char const *를 증분하고 역 참조 char하여 int.


"hello"그리고 "stack"둘 다 InputIterator 개념 const char *을 만족시키는 붕괴 입니다. 이렇게하면 생성자 # 4 와 일치 할 수 있습니다 .std::vector

std::string객체 를 전달 하면 모호성이 해결됩니다.

참고 URL : https://stackoverflow.com/questions/41507602/why-does-the-number-of-elements-in-a-initializer-list-cause-an-ambiguous-call-er

반응형