Passing a template callback function to another template function

I try to pass my callback function compto my template function quickSortR, but I get the following error:

2 IntelliSense: no instance of function template "quickSortR", corresponding to the list of arguments"

When I uncomment the code at the top, I get another list of errors. So, I think the problem is the misuse of my callback function.

#include<stdio.h>

/* 
 template<class T> 
 int comp(const void*, const void*);
 template<class T>
 void quickSortR(T* a, long N, int comp(const void*,const void*));
 Here is my instance. I commented it. 
*/ 


template<class T> 
int comp(const void* a, const void* b)
{

    return (*(T*)a - *(T*)b);
}

template<class T>
void quickSortR(T* a, long N, int comp(const void*,const void*)) {


    long i = 0, j = N;      
    T temp, p;

    p = a[ N>>1 ];      

    do {
        while ( !comp(*a[i],*p) ) i++;
        while ( comp(*a[j],*p) ) j--;

        if (i <= j) {
            temp = a[i]; a[i] = a[j]; a[j] = temp;
            i++; j--;
        }
    } while ( i<=j );


    if ( j > 0 ) quickSortR(a, j, comp);
    if ( N > i ) quickSortR(a+i, N-i, comp);
}

int main() {
    int n;
    int m[10] = {1,-3,5,-100,7,33,44,67,-4, 0};

    //problem is on this line
    quickSortR<int>(m, 10, comp);

    for (n=0; n<10; n++)
        printf ("%d ",m[n]);

    return 0;
}
+4
source share
1 answer

There are several problems you can fix to compile

a. Replace

quickSortR<int>(m, 10, comp);

from

quickSortR<int>(m, 10, comp<int>);

B. Another in

while ( !comp(*a[i],*p) ) i++;
while ( comp(*a[j],*p) ) j--;

Replaced by

while ( !comp(&a[i],&p) ) i++;
while ( comp(&a[j],&p) ) j--;

how it comptakes pointers, not value. Fully test this logic.

However, this will only solve compiler errors, not logical errors.

+3

All Articles