将模板化回调函数传递给另一个模板化函数

时间:2013-12-08 09:06:25

标签: c++ templates

我试图将回调函数comp传递给我的模板函数quickSortR但是出现以下错误:

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

当我取消注释顶部的代码时,我得到另一个错误列表。所以,我认为问题在于我的回调函数使用错误。

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

1 个答案:

答案 0 :(得分:3)

您可以修复一些问题来编译

一个。取代

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

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

B中。

中的另一个
while ( !comp(*a[i],*p) ) i++;
while ( comp(*a[j],*p) ) j--;

替换为

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

因为comp正在指点,而不是价值。彻底检查这个逻辑。

但是,这只能解决编译错误而不是逻辑错误。

相关问题