2013-03-27 39 views
0

我有以下代码。重载模板函数调用不明确

#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 

为什么会出现这种情况,以及最好的补救方法是什么?

回答

2

您的代码

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。因此编译器变得困惑。 可以有解决办法。但既然你需要最好的解决方案,我会说重命名你的最​​大功能,如MAximum。

+0

谢谢。这是有道理的。 – idealistikz 2013-03-27 19:05:04

3

问题是编译器通过ADL找到max的多个匹配定义,并且它不知道选择哪个。

尝试改变调用max利用其合格ID:

std::string smax = ::max(max(svec),max(sarray,6)); 
+1

@idealistikz这是因为你有一个错字,只是删除该行上的额外分号。 – 2013-03-27 18:59:56

+0

如何使它与我定义的函数'max'一起工作,因为它与其他类型一起工作? – idealistikz 2013-03-27 19:00:58

+1

它与其他类型一起工作,因为它们不像'std :: string'那样生活在'std'命名空间中。或者以不同的方式命名你的功能'my_max')或者像我所显示的那样使用它的合格id。 – 2013-03-27 19:02:43

0

这是为什么出现?
编译器错误已经告诉你为什么。它不知道要使用哪个版本的max

注:候选是:
main.cpp中:6:38:注意:类型MAX(类型,类型)[与类型=标准:: basic_string的]
...
的/ usr /包括/c++/4.7/bits/stl_algobase.h:210:5:注:常量_TP &的std ::最大(常量_TP &,常量_TP &)[与_TP =标准:: basic_string的]

解:
或者直接调用你的max函数,或者直接调用std::max(它已经存在,那么为什么要重新实现呢?)。

此外,还有一个;<< "fmax should be 24.8 -- found: " << fmax << '\n'

+0

我想重新实现它,因为我试图理解模板函数。 – idealistikz 2013-03-27 19:03:18

+0

好的,这是一个很好的理由 – Misch 2013-03-27 19:26:18