boost::bind实现原理学习

来源:互联网 发布:ubuntu解压tar文件 编辑:程序博客网 时间:2024/05/21 19:33

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

在这个时间点,让我也有时间在工作时间了学习一把。对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;}



 

原创粉丝点击