函数模板问题(带一个函数指针参数)

syscoder 2005-08-03 03:09:34
主要就是想实现一个通用的排序函数:
void QuickSort( type * front, type * end, int(*compare)( const type & var1, const type & var2) )
前两个参数指向需要比较的头尾两个指针,第三个为一个函数指针,指向一个用于比较元素的函数(元素可以是整形、字符......),若var1小与var2则返回-1,大于返回1,等于返回0。假设现在对一个string数组按每个字符串长度进行排序,先给出一个比较函数:
int SizeCompare( const string & st1, const string & st2 ){
if( st1.size() == st2.size() )
return 0;
else
return (st1.size() < st2.size()) ? -1:1;
}
然后定义一个字符串数组string test[10];
调用排序函数:
QuickSort( test, test + sizeof( test )/sizeof( test[0] ) - 1, SizeCompare );
可是vc6编译时总是出错:
error C2782: 'void __cdecl QuickSort(type *,type *,int (__cdecl *)(const type &,const type &))' : template parameter 'type' is ambiguous
哪位高手指点一下,感激不尽!
...全文
157 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
syscoder 2005-08-04
  • 打赏
  • 举报
回复
嗯,试了,.net下也没有问题,奇怪ing...
BillSmith 2005-08-03
  • 打赏
  • 举报
回复
没有用。
去了它ok!
syscoder 2005-08-03
  • 打赏
  • 举报
回复
#include "stdafx.h"
这个同文件在这个例子中有什么作用吗?
不包括这个头文件也可以通过吗?
healer_kx 2005-08-03
  • 打赏
  • 举报
回复
// TypeWrapper.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>

using namespace std;

template<class type>
void QuickSort( type * front, type * end, int(*compare)( const type & var1, const type & var2) )
{

}

int SizeCompare( const string & st1, const string & st2 )
{
if( st1.size() == st2.size() )
return 0;
else
return (st1.size() < st2.size()) ? -1:1;
}



int main()
{

string test[10];

QuickSort(test, test + 10, SizeCompare);

return 0;
}

全文编译通过,没有出现问题啊。我是VC7的。。。6没有试验。




65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧