2013-03-27 66 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