其本质就是用来执行方法(函数)的一个东西。
#include <stdio.h>
#include "fastdelegate.h"
typedef fastdelegate::FastDelegate2<int, int, int> AddFunc;
typedef fastdelegate::FastDelegate1<string> DoSomeThingFunc;
class Demo
{
public:
int Add(int a, int b)
{
return a + b;
}
int DoSomeThing (string &str)
{
//do some thing
}
};
class HandleDemo
{
public:
template <class X, class Y, class Param1, class Param2, class RetType>
void bind_add(Y* x, RetType (X::*func)(Param1 p1, Param2 p2))
{
pAddFunc = fastdelegate::MakeDelegate(x, func);
}
template <class X, class Y, class Param1, class RetType>
void bind_do(Y* x, RetType (X::*func)(Param1 p1))
{
pDoSomeThingFunc = fastdelegate::MakeDelegate(x, func);
}
public:
void Init(Demo *pDemo)
{
bind_add(pDemo, &Demo::Add);
bind_do(pdemo, &Demo::DoSomeThing );
}
void ExecuteAdd(int a, int b)
{
int Sum = pAddFunc(a, b);
printf("Sum=%d\n", Sum);
}
void ExecuteDo(String str)
{
pDoSomeThingFunc (str);
}
private:
AddFunc pAddFunc;
DoSomeThingFunc pDoSomeThingFunc ;
};
int main(int argc, char* argv[])
{
Demo demo;
HandleDemo handldemo;
handldemo.Init(&demo);
//执行函数,调用绑定函数
handldemo.ExecuteAdd(200, 100);
handldemo.ExecuteDo("hello!");
return 0;
}
相当于demo 委托handledemo来执行它的功能函数,ExecuteAdd 和ExecuteDo实际执行的是Add ,DoSomeThing