boost库 bind实现思路简易版本(去模板化)

来源:互联网 发布:消失的夫妻 知乎 编辑:程序博客网 时间:2024/06/06 08:27

boost::bind 是标准函数 std::bind1st 和 std::bind2nd 的泛化。它支持任意的函数对象,函数,函数指针,和成员函数指针,它还能将任何参数绑定为一个特定的值,或者将输入的参数发送到任意的位置。
具体介绍内容官网:http://www.boost.org/doc/libs/1_53_0/libs/bind/bind.html (英文) 和 我上次分享出来的中文翻译文档( http://www.cctry.com/thread-266663-1-1.html )有详细介绍,例子可以百度找找。先举一个使用的简单例子:

#include <iostream>#include <boost/function.hpp>#include <boost/bind.hpp>#include <boost/lambda/lambda.hpp>class test1{public:  test1() {}  test1(const test1& p) {}  ~test1() {}  void do_something(int& i, int& j)  {    i = 9;    j = 11;  }};int main(){  test1 t1;  int x = 0, y = 0;  boost::bind(&test1::do_something,  t1, boost::lambda::_1, boost::lambda::_2)(x, y);  //还有种方法是混合function库使用,下文会介绍  return 0;}

下面是到了正餐了,去模板的bind简易实现:

#include <vector>#include <algorithm>#include <iterator>#include <iostream>namespace{class placeholder {};placeholder _1;}class Test{public:  Test() {}  Test(const Test& p) {}  ~Test() {}  void do_stuff(const std::vector<int>& v)  {    std::vector<int>::const_iterator it = v.begin();    for (; it != v.end(); ++it) {      std::cout << *it << std::endl;    }  }};class simple_bind_t{  typedef void(Test::*fn)(const std::vector<int>&);  fn fn_;  Test t_;public:  simple_bind_t(fn f, const Test& t): fn_(f), t_(t)  {    int i = 0;  }  ~simple_bind_t()  {    int i = 0;  }  void operator()(const std::vector<int>& a)  {    return (t_.*fn_)(a);  }};simple_bind_t simple_bind(void(Test::*fn)(const std::vector<int>&),                          const Test& t, const placeholder&){  return simple_bind_t(fn, t);}int main(){  Test t;  std::vector<int> vec;  vec.push_back(42);  simple_bind(&Test::do_stuff, t, _1)(vec);   return 0;}

boost中的bind 主要思路是保存传递进来的函数地址和class对象t,在调用的地方调用重载函数 void operator(),
若使用boost库function函数,可以把 这行 simple_bind(&Test::do_stuff, t, _1)(vec);替换成如下实现方式

boost::function<void(const std::vector<int>&)> fun(simple_bind(&Test::do_stuff, t, _1);// ... do somethingfun(vec);
0 0
原创粉丝点击