Michael Metreveli
Michael Metreveli

Reputation: 111

Template problems

I have this simple sort program which should work for vector of Set<int>-s , it works for primitive types and I use some other compare functions for non primitives and it works well, but once I try to compare sets it crashes with error:

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

How can I fix this?

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

Upvotes: 1

Views: 69

Answers (3)

Barry
Barry

Reputation: 302643

You have a type mismatch. bozoSort is declared as:

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

When you call it with a, you are hoping to deduce T = Set<int> >, which would be the signature:

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

However, you're calling it with compareSets, which has the signature int (Set<int>&, Set<int>&). Those don't match, so the compiler can't resolve the template for you. The better solution would be just to take the whole comparator as a template:

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

That way, if you want your comparator to take its arguments by reference, const reference, or value - any of the above will work just fine.

Upvotes: 2

Columbo
Columbo

Reputation: 60969

type is deduced as a reference to Set<int> for the function pointer parameter and Set<int> for the value type of the container, which is an inconsistent deduction. The easiest solution: Completely generalize the functor:

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

.. and overload for the one-parameter case.

Upvotes: 2

Daniel Frey
Daniel Frey

Reputation: 56863

You have

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

and you are calling it with

vec = Vector<Set<int>>

and

cmp = compareSets

which is

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

Now for vec, type can only be Set<int>, while for cmp, type can only be Set<int>&. Both don't go together, hence the error.

Upvotes: 1

Related Questions