您的位置:首页 > 编程语言 > C语言/C++

C++ 委托 fastdelegate

2017-07-20 14:00 323 查看
fastdelegate 是c++实现的快速委托机制,
其本质就是用来执行方法(函数)的一个东西。

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: