2015-05-19 98 views
1

我有這個簡單的排序程序,它應該適用於矢量Set<int>-s,它適用於原始類型,我使用一些其他比較函數用於非基元,它運行良好,但是一旦我嘗試比較設置,它崩潰有錯誤:模板問題

error C2782: 'void Sort(Vector<ElemType> &,int (__cdecl *)(type,type))' : template parameter 'type' is ambiguous

我該如何解決這個問題?

template <typename type> 
void swap(int &a, int &b){ 
    type tmp =a; 
    a = b; 
    b = tmp; 
} 


template <typename type> 
void Sort(Vector<type>& vec,int (cmp) (type,type) = OperatorCmp){ 
    while(true){ 
     for(int i =1; i < v.size(); i++){ 
     if(cmp(v[i-1],v[i]) > 0){ 
      break; 
      }else{ 
      return; 
     } 
    } 

     int index1 = RandomInteger(0,vec.size()-1); 
     int index2 = RandomInteger(0,vec.size()-1); 
     swap(vec[index1],vec[index2]); 
    } 
} 


int main(){ 
    Randomize(); 
    Vector<char>a; 

    Sort(a); 


    return 0; 
} 
+0

我不認爲演繹可以在這裏工作。 –

+0

這遠不是**最小**,**完整**例子。 – Barry

+1

@LightnessRacesinOrbit它的確如此。它只是產生不一致的扣除。 – Columbo

回答

2

您有類型不匹配。 bozoSort聲明爲:

template <typename T> 
void bozoSort(Vector<T>& vec, int (cmp) (T,T)); 

當你與a調用它,你都希望能夠推斷T = Set<int> >,這將是簽名:

void bozoSort(Vector<Set<int> >& vec, int (cmp) (Set<int>, Set<int>)); 

但是,你與compareSets調用它,這有簽名int (Set<int>&, Set<int>&)。那些不匹配,所以編譯器無法爲您解析模板。較好的解決辦法是隻取整比較作爲模板:

template <typename T, typename Compare> 
void bozoSort(Vector<T>& vec, Compare cmp) { ... } 

這樣,如果你希望你的比較參照,const引用,或價值採取它的參數 - 上述任何將只是工作精細。

1

你有

template <typename type> 
void bozoSort(Vector<type>& vec,int (cmp) (type,type) = OperatorCmp) 

,你與

vec = Vector<Set<int>> 

cmp = compareSets 

這是

叫它210
int compareSets(Set<int>& a , Set<int>& b){ 

現在對於vectype只能是Set<int>,而對於cmptype只能是Set<int>&。兩者不會在一起,因此錯誤。

2

type被推斷爲對函數指針參數的Set<int>和對容器的值類型Set<int>的參考,這是不一致的推導。最簡單的解決方案:完全推廣仿函數:

template <typename type, typename Fun> 
bool isSorted(Vector<type> & vec, Fun cmp){ 
    for(int i =0; i < vec.size()-1; i++){ 
     if(cmp(vec[i],vec[i+1]) > 0)return false; 
    } 
    return true; 
} 

..以及單參數情況下的過載。