boost::bind实现原理学习

    公司最近商业模式转变,很多项目都被暂停了,我们项目也是在暂停之列,而且部门同事也被裁掉一半。

在这个时间点,让我也有时间在工作时间了学习一把。对boost::bind学习的时候,顺便看到一边关于bind实现原理的讲解,在里面看到了在类中使用模板方式定义一个回调函数,于是想验证一把,但发现模板回调函数居然不能是全局的。可以在类里面定义,可以在函数参数里面定义。具体原因不是清楚。下面是对该bind函数实现原理的代码。原博客对bind的实现机制描述得非常透彻,忘了博客地址,不然是应该要贴出来的。在里面还涉及到我以前不知道int-To-Type的知识,主要是我对模板这块还不熟悉。下面看看代码吧

 

//testtemplatecallback.h

#include <iostream>
#include <string>

using namespace std;

template<typename X, typename Y>
class TestCallBack
{
	typedef X (*P_FN)(Y);
public:
	TestCallBack(P_FN pfn):m_pFn(pfn){}
	void operator()()
	{
		m_pFn(2);
	}
private:
	P_FN m_pFn;
};

/*
//可以在类中使用回调函数模板,而不能定义全局回调函数模板
//错误如下:
//error C2823: typedef 模板 非法
//error C2998: “P (__cdecl *__cdecl P_FNZ)(Q)”: 不能是模板定义

template<typename P,typename Q>
typedef P (*P_FNZ)(Q);
*/

//这个能够行
template<typename M, typename N>
int FuncCallBack(M (*P_pFN)(N))
{
	return P_pFN(1);
}
int HelloCallBack(int )
{
	cout<<"hello world"<<endl;
	return 0;
}
void TestCall_Back()
{
	TestCallBack<int,int> TCB(HelloCallBack);
	TCB();
	FuncCallBack(HelloCallBack);

}

 

下面就是bind库结合STL中的find_if的使用例子了,说实话对于C++的模板实现的东西,让我们的代码变简洁了,但同时也增加了代码的理解复杂度。

#include <string>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>

using namespace std;
using namespace boost;

class Person
{
public:
	Person(const string& name)
		: name_(name)
	{}

	string Name()
	{
		return name_;
	}

	string name_;
};

void TestBind()
{
	typedef vector<Person> PersonList;

	PersonList personList;
	personList.push_back(Person("Ralph"));
	personList.push_back(Person("Joy"));
	personList.push_back(Person("Martin"));

	PersonList::iterator iter = 
		find_if(personList.begin(), personList.end(),
		bind(&Person::Name, _1) == "Ralph");

	cout << (iter == personList.end() ? "Not found." 
		: iter->Name().append(" found."))
		<< endl;
}



 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值