C++利用boost::bind实现“委托”

作者:朱之光

C#中的委托有两种绑定方式:

1、绑定到类方法
2、绑定到静态类方法

绑定到静态方法很容易,用一个函数指针就可以实现;而绑定到类方法,就需要考虑传递一个对象实例的参数。
利用boost::bind可以很容易的实现这两类绑定,从而实现类似“委托”执行机制。

#include <boost/bind.hpp>
#include <boost/function.hpp>

#define DELEGATE_DECLARE(name, signature) typedef boost::function< signature > name

#define BIND_DEL2MEMFUNC_0(cls_memfunc, inst) boost::bind(&cls_memfunc, inst)
#define BIND_DEL2MEMFUNC_1(cls_memfunc, inst) boost::bind(&cls_memfunc, inst, _1)
#define BIND_DEL2MEMFUNC_2(cls_memfunc, inst) boost::bind(&cls_memfunc, inst, _1, _2)
#define BIND_DEL2MEMFUNC_3(cls_memfunc, inst) boost::bind(&cls_memfunc, inst, _1, _2, _3)

#define BIND_DEL2STCFUNC_0(cls_stcfunc) boost::bind(&cls_stcfunc)
#define BIND_DEL2STCFUNC_1(cls_stcfunc) boost::bind(&cls_stcfunc, _1)
#define BIND_DEL2STCFUNC_2(cls_stcfunc) boost::bind(&cls_stcfunc, _1, _2)
#define BIND_DEL2STCFUNC_3(cls_stcfunc) boost::bind(&cls_stcfunc, _1, _2, _3)

//声明一个委托类型 void Delegate1(int, int)
DELEGATE_DECLARE(Delegate1, void (int, int)); 

class A
{
public:
  void DoSomething(int a, int b, int c)
  {
  //遍历链表
  for (std::list::iterator it = m_delegates.begin(); it != m_delegates.end(); it++)
  {
    (*it)(a, b);
  }
}

public:
  std::list m_delegates; //形成一个多播委托
};

class B
{
public:
  static void TestFunc1(int val1, int val2)
  {
    cout << "TestFunc1 : ";
    cout << val1 << " " << val2 << endl;
  }

  void TestFunc2(int val1, int val2)
  {
    cout << "TestFunc2 : ";
    cout << val1 << " " << val2 << endl;
  }

  void TestFunc3(int val1, int val2)
  {
    cout << "TestFunc3 : ";
    cout << val1 << " " << val2 << endl;
  }
};

int _tmain(int argc, _TCHAR* argv[])
{
  B b;
  A a;

  //由于Delegate1需要两个参数,所以选用BIND_DEL2STCFUNC_2;如果需要三个参数,则选择BIND_DEL2STCFUNC_3
  a.m_delegates.push_back(BIND_DEL2STCFUNC_2(B::TestFunc1));     //绑定到静态方法
  a.m_delegates.push_back(BIND_DEL2MEMFUNC_2(B::TestFunc2, &b)); //绑定到普通类方法
  a.m_delegates.push_back(BIND_DEL2MEMFUNC_2(B::TestFunc3, &b)); //绑定到普通类方法

  a.DoSomething(1, 2, 3); //执行过程中会实现“委托”执行

  return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值