protobuf里面的回调函数

刚开始看protobuf的时候把这些关键部分提出来写一遍,大概的思想和代码逻辑就能理清楚了

 

#include <iostream>
#include <functional>

using namespace std;

class Closure
{
public:
	Closure() {};
	~Closure() {};

	virtual void Run() = 0;
};

template<typename Class, typename Arg1, typename Arg2>
class MethodClosure2 : public Closure
{
public:
	typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2);

	MethodClosure2(Class* object, MethodType method, bool self_deleting,
		Arg1 arg1, Arg2 arg2) :object_(object), method_(method), self_deleting_(self_deleting),
		arg1_(arg1), arg2_(arg2) {}
	~MethodClosure2() {}

	void Run()
	{
		(object_->*method_)(arg1_, arg2_);
		if (self_deleting_)
		{
			delete this;
		}
	}

private:
	Class* object_;
	MethodType method_;
	bool self_deleting_;
	Arg1 arg1_;
	Arg2 arg2_;
};

template<typename Class, typename Arg1, typename Arg2>
Closure* NewCallBack(Class *object, void (Class::*method)(Arg1, Arg2), Arg1 arg1, Arg2 arg2)
{
	return new MethodClosure2<Class, Arg1, Arg2>(object, method, true, arg1, arg2);
}

class A
{
public:
	A() {}
	void RPCCallBack(int arg1, int arg2)
	{
		cout << arg1 << " " << arg2 << endl;
	}
};

int main(int argc, char* argv[])
{
	A *a = new A();
	auto done = NewCallBack(a, &A::RPCCallBack, 3, 4);

	done->Run();

	system("pause");
	return 0;
}

 

在源码的基础上用C++11的function和bind把原有的函数指针代替了,代码如下

#include <iostream>
#include <functional>
using namespace std;

class Closure
{
public:
	Closure() {};
	~Closure() {};

	virtual void Run() = 0;
};

template<typename Arg1, typename Arg2>
class MethodClosure2 : public Closure
{
public:
	typedef std::function<void(Arg1, Arg2)> MethodType;

	MethodClosure2(MethodType method, bool self_deleting,
		Arg1 arg1, Arg2 arg2) :method_(method), self_deleting_(self_deleting),
		arg1_(arg1), arg2_(arg2) {}
	~MethodClosure2() {}

	void Run()
	{
		method_(arg1_, arg2_);
		if (self_deleting_)
		{
			delete this;
		}
	}

private:
	MethodType method_;
	bool self_deleting_;
	Arg1 arg1_;
	Arg2 arg2_;
};

template<typename Arg1, typename Arg2>
Closure* NewCallBack(std::function<void (Arg1, Arg2)> func, Arg1 arg1, Arg2 arg2)
{
	return new MethodClosure2<Arg1, Arg2>(func, true, arg1, arg2);
}

class A
{
public:
	A() {}
	void RPCCallBack(int arg1, int arg2)
	{
		cout << arg1 << " " << arg2 << endl;
	}
};

int main(int argc, char* argv[])
{
	A *a = new A();
	std::function<void(int, int)> func = std::bind(&A::RPCCallBack, a, std::placeholders::_1, std::placeholders::_2);

	auto done = NewCallBack(func, 3, 4);
	done->Run();
	
	system("pause");
	return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值