반응형
이니셜 라이저 목록의 요소 수가 모호한 호출 오류를 일으키는 이유는 무엇입니까?
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::string
s이므로 모호함이 없습니다.
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
객체 를 전달 하면 모호성이 해결됩니다.
반응형
'developer tip' 카테고리의 다른 글
ReactDOM은 어디에서 가져와야합니까? (0) | 2020.12.12 |
---|---|
C / C ++ 기본 유형은 원자 적입니까? (0) | 2020.12.12 |
asp.net 코어 미들웨어 대 필터 (0) | 2020.12.12 |
iPhone의 Application Delegate의 적절한 사용 (0) | 2020.12.12 |
고주파 거래 (0) | 2020.12.12 |