gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:56 25 4
gpt4 key购买 nike

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

2 IntelliSense:没有函数模板“quickSortR”的实例,对应于参数列表

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

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

最佳答案

编译时可以解决的问题很少

一个。替换

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 接受的是指针,而不是值。彻底检查这个逻辑。

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

关于c++ - 将模板化回调函数传递给另一个模板化函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20451638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com