1
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?

4
  • C++ does not have generics, it has templates. The two may look the same, but they work in fundamentally different ways. Commented Apr 21, 2012 at 14:36
  • Mine compiled when I changed compare(T,T) to compare (const T &, const T &) and commented out the zamien line. Changing zamien to std::swap produced correct results when the numbers were different at least. Commented Apr 21, 2012 at 14:40
  • @Jasper but you use templates to do generic programming :-) Commented Apr 21, 2012 at 14:44
  • 2
    I suppose. But C++ Templates is an ugly-ass bodybuilder who can lift cars, while generics are just an average Joe that happens to be good at dressing up... Commented Apr 21, 2012 at 14:47

2 Answers 2

2

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&)){
    /* ... */
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have still that error: 'void bubble_sort(T [],int,bool (__cdecl *)(const T &,const T &))' : could not deduce template argument for 'T []' from 'int [10]' when I want to use it like: bubble_sort(tab, size, cmp), where tab[] = {0,1,2,3,4,5,6,7,8,9}.
Ok, on ideone it works perfectly, but when I try to compile it in MS Visual 2010 I have errors.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.