Finley Osbert
Finley Osbert

Reputation: 103

Sorting an array with own template compare function in C++

template <class T>
bool cmp(const T &a, const T &b){
    return a <= b;
}

template <class T>
void bubble_sort(T tablica[], int size, bool compare(T,T)){
    bool change = true;

    while(change){
        change = false;
        for(int i=0; i < size-1; ++i){
            if(compare(tablica[i+1], tablica[i])){
                zamien(tablica[i+1], tablica[i]);
                change = true;
            }
        }
    }
}

It doesn't work, I have errors:

'void bubble_sort(T [],int,bool (__cdecl *)(T,T))' : 
 could not deduce template argument for 'T []' from 'int [10]'  
'void bubble_sort(T [],int,bool (__cdecl *)(T,T))' :
 cannot use function template 'bool cmp(const T,const T)' as a function argument'

but when I replace a cmp function with that:

bool cmp(const int a, const int b){
    return a <= b;
}

Everything works fine. How to change my cmp function to work with templates?

Upvotes: 1

Views: 3114

Answers (2)

Finley Osbert
Finley Osbert

Reputation: 103

This is how I handled with this problem:

int (*cmp_int)(int,int) = compare<int>;
bubble_sort(in, 5, cmp_int);

Now it should work fine in MS Visual.

Upvotes: 0

mfontanini
mfontanini

Reputation: 21900

The problem is that the "compare" function parameter that bubble_sort expects is of type:

bool compare(T,T)

While the "cmp" function is of type:

bool compare(const T&,const T&)

In order to fix it, modify the "compare" parameter's type:

template <class T>
void bubble_sort(T tablica[], int size, bool compare(const T&,const T&)){
    /* ... */
}

Upvotes: 2

Related Questions