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
- boost库 bind实现思路简易版本(去模板化)
- boost bind 实现方法
- boost bind 实现方法
- boost bind 实现方法
- boost bind 实现方法
- Boost库之bind
- 实现简易版js bind
- boost::bind实现原理学习
- 怎样用boost::serialization去序列化派生模板类
- 怎样用boost::serialization去序列化派生模板类(续)
- Boost::Bind 库 之bind(1)
- 【Boost】boost库中bind的用法
- 模板实现简易stack
- 模板实现简易queue
- 用boost实现的一个简易线程池库
- 详细解析boost中bind的实现
- 详细解析boost中bind的实现 .
- 在VC6中实现Boost::Bind/Function
- (一)算法——冒泡排序、选择排序
- css知识点2
- Android-support-v4源码导入项目按钮无法显示
- 缩放系列(三):一个可以手势缩放、拖拽、旋转的layout
- memcache与memcached的概念、区别的相关解释
- boost库 bind实现思路简易版本(去模板化)
- 磁盘与目录的容量
- 出书之一【反射技术】
- 更改时间格式
- 共享可变性设计中存在风险以及解决方法(三)
- bzoj 4688: One-Dimensional 矩阵乘法
- kettle学习日记(1)
- 题目1078:二叉树遍历
- js案例-2 左右select栏目内容互换