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

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 something
fun(vec);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值