[英]Call of overloaded template function is ambiguous
我有以下代码。
#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;
}
我正在尝试实现两个简单的模板函数,以输出向量和数组的max元素。 但是,当类型为字符串时,我收到以下错误。
error: call of overloaded 'max(std::string, std::string)' is ambiguous
为什么会发生这种情况?补救的最佳方法是什么?
问题在于,编译器正在通过ADL查找max
多个匹配定义,并且它不知道选择哪个。
尝试将呼叫更改为max
以使用其限定ID:
std::string smax = ::max(max(svec),max(sarray,6));
您的密码
std::string smax = max(max(svec),max(sarray,6));
转换为:
std::string smax = max(string ,string );
使用模板评估max(svec)
和max(sarray,6)
。 现在出现问题了:标准库已经带有模板化的max()函数。 编译器将无法判断您是否要使用max()
或std::max()
。 现在,您将问为什么它适用于整数和浮点数。 答案是在这行中,您特别提到了std::string
。 因此,编译器变得混乱。 可以有工作环境。 但是,由于您需要最好的解决方案,因此我想将您的max函数重命名为MAximum。
为什么会这样呢?
编译器错误已经告诉您原因。 它不知道使用哪个版本的max
。
注意:候选人是:
main.cpp:6:38:注意:Type max(Type,Type)[with Type = std :: basic_string]
...
/usr/include/c++/4.7/bits/stl_algobase.h:210:5:注意:const _Tp&std :: max(const _Tp&,const _Tp&)[with _Tp = std :: basic_string]
解:
要么显式调用您的max
函数,要么仅调用std::max
(该函数已经存在,那么为什么要重新实现它?)。
另外,还有一个;
<< "fmax should be 24.8 -- found: " << fmax << '\\n'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.