模板的问题

Template problems

本文关键字:问题      更新时间:2023-10-16

我有这个简单的排序程序,它应该适用于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;
}

类型不匹配。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引用或value获取参数,那么上述任何一种方法都可以很好地工作。

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;
}

. .

你有

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

调用
vec = Vector<Set<int>>

cmp = compareSets

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

现在对于vec, type只能是Set<int>,而对于cmp, type只能是Set<int>&