다음 코드가 있습니다.오버로드 된 템플릿 함수 호출이 모호합니다.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
template <typename Type> inline Type max(Type t1, Type t2) {
return t1 > t2 ? t1 : t2;
}
template <typename Type> inline Type max(const std::vector<Type> &vec) {
return *std::max_element(vec.begin(),vec.end());
}
template <typename Type> inline Type max(const Type *parray, int size) {
return *std::max_element(parray,parray+size);
}
int main(int argc, char *argv[]) {
std::string sarray[] = {"we","were","her","pride","of","ten"};
std::vector<std::string> svec(sarray,sarray+6);
int iarray[] = {12,70,2,169,1,5,29};
std::vector<int> ivec(iarray,iarray+7);
float farray[] = {2.5,24.8,18.7,4.1,23.9};
std::vector<float> fvec(farray,farray+5);
int imax = max(max(ivec),max(iarray,7));
float fmax = max(max(fvec),max(farray,5));
std::string smax = max(max(svec),max(sarray,6));
std::cout << "imax should be 169 -- found: " << imax << '\n'
<< "fmax should be 24.8 -- found: " << fmax << '\n'
<< "smax should be were -- found: " << smax << '\n';
return 0;
}
벡터와 배열의 최대 요소를 출력하는 두 개의 간단한 템플릿 함수를 구현하려고합니다. 그러나 형식이 문자열 인 경우 다음과 같은 오류가 발생합니다.
error: call of overloaded 'max(std::string, std::string)' is ambiguous
왜 이런 현상이 발생하며이를 해결하는 가장 좋은 방법은 무엇입니까?
고마워. 이것은 의미가 있습니다. – idealistikz