作者:朱之光
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;
}