c++ 函数指针模板

[size=large]直接按如下定义是不行的,会报错!!![/size]
typedef  template<class T> bool (*templateFunc)(const T& t1,const T& t2); //编译不通过!!!


[size=large]但是不意味着不可以以模板函数作为函数的参数!!!回顾函数指针时[/size][url]http://cherishlc.iteye.com/blog/1274062[/url]
[size=large]发现了返回函数指针的函数可以如下声明:[/size]
int (*fff(int a))(int ,int){//从函数名开始向外读  
return sub;
}


[color=blue][size=large]经过测试,以下函数中的可以传递函数指针的模板了~~~~~[/size][/color]

#include <iostream>

using namespace std;

template<class T> inline bool isEqual(const T& t1,const T& t2){
return t1==t2;
}

//typedef template<class T> bool (*templateFunc)(const T& t1,const T& t2); //编译不通过!!!

//第三个参数为以T为参数的函数,不可按上述方法定义!!!但直接写就没问题
template<class T> bool isEqual2(T t1,T t2,bool (*isCompatible)(const T&,const T&)=isEqual<T>){
return isCompatible(t1,t2);
}

void main(){
bool (*isIntEqual)(int,int);
//isIntEqual=isEqual2<int>; //不行,真悲催
bool not=isEqual2<int>(1,2);
bool yes=isEqual2<double>(1.0,1.0);
cout<<"1==2? "<<not<<"\n1.0==1.0? "<<yes<<endl;
}



[size=large]另外转载两个其他的方法:
1、[/size][url]http://topic.csdn.net/u/20120418/00/64c2d59b-151b-450e-a7aa-39ff6bf941a5.html?seed=380167928&r=78289909[/url]
template <typename PktType>
struct Wrapper
{
typedef int (* CallbackFunPtrType) (const PktType& CurPkt);
};
这样不就行了
用的时候就
Wrapper<int>::CallbackFunPtrType callback=....


[size=large]2、C++中用模板函数指针实现委托[/size][url]http://tangfeng.iteye.com/blog/602680[/url]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值