C++委托实现(函数指针,function+bind,委托模式)

本文探讨了C++中的函数指针、boost::bind和boost::function的使用,以及它们如何实现委托模式。介绍了函数指针的声明和使用,以及bind和function如何简化代码,提供更强大的功能。此外,还阐述了委托模式的概念,强调了代理对象在控制对实体访问中的作用。
摘要由CSDN通过智能技术生成

  这一段在公司的某个框架代码中看到了函数指针的使用。风格比较偏纯C,其实C++有更加合适的解决方案,在这里总结一下。
  首先从函数指针说起。
  
  一、函数指针
  从定义上讲,函数指针指向的是函数而非对象,函数指针指向某种特定类型。其类型由函数的返回类型和形参类型决定。
  声明方式如下:

bool (*pf)(const string &,const string &);

  注意pf两侧的括号不能少,不然就变成了单纯的返回值为指针类型的函数声明。
  使用方式如下:
  

bool lengthCompare(const string &a,const string &b){
  return a.size()<b.size();
}
  //same as pf = &lengthCompare
  pf = lengthCompare;

  bool b1= pf("hello","fun");
  cout<<b1<<endl;

  //这两个是等价的调用
  bool b2 = (*pf)("hello","goodBye");
  cout<<b2<<endl;

当然,函数指针也可以作为形参使用,用法如下:

void big(const string &a,const string &b,
          bool (*pf)(const string &,const string &)){
//same as bool pf(const string &,const string &)
  cout<<pf(a,b)<<endl;            
}

如果嫌弃参数的表达式过于冗长,可以使用typedef定义类型。

typedef bool func(const string &,const string &);
typedef bool (*funcP) (const string &,const string &);

因为在作为参数传递的时候,函数类型会被自动转换为指针,因此有以下两种用法。

void small(const string &a,const string &b,funcP fp){
  bool res=fp(a,b);
  cout<<!res<<endl;
}
void smallTwo(const string &a,const string &b,func fp){
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值