function object研究之六 bind example
来源:互联网 发布:python程序是什么 编辑:程序博客网 时间:2024/06/05 07:10
这个系列主要希望弄明白boost::bind的实现原理,回到研究之四的简单使用的例子。稍微加点代码,也绑定Foo函数。
#include <iostream>#include <vector>#include <algorithm>#include <boost/bind.hpp>using namespace std;bool Foo(int x) { return x >= 2;}typedef bool (*FooPointer)(int x);int main(int argc, char** argv) { FooPointer p = Foo; vector<int> v; v.push_back(1); v.push_back(2); // bind Foo function vector<int>::iterator itor = std::find_if(v.begin(), v.end(), boost::bind(Foo, _1)); cout << *itor << endl; // bind FooPointer itor = std::find_if(v.begin(), v.end(), boost::bind(p, _1)); cout << *itor << endl; return 0;}两次查找分别使用了Foo函数和FooPointer函数指针。
boost提供了一些bind重载模板函数,bind实际上是通过宏出现的,在bind.hpp中如下定义:
#ifndef BOOST_BIND#define BOOST_BIND bind#endif
第一个bind(foo, _1)用到了下面的重载形式:
template<class R, class F, class A1> _bi::bind_t<R, F, typename _bi::list_av_1<A1>::type> BOOST_BIND(F f, A1 a1){ typedef typename _bi::list_av_1<A1>::type list_type; return _bi::bind_t<R, F, list_type> (f, list_type(a1));}所以这里F f就是指的Foo函数, 这个地方有点意思,因为函数Foo居然可以像类型一样作为模板参数传递。我以前从未这样用过。
迅速做个实验:
template <typename F>void Test(F f){ cout << f(2);}
int main(int argc, char** argv) { Test(Foo); return 0;}编译运行成功,输出结果为1.
A1 a1指的是外面调用代码传递进来的_1.
- function object研究之六 bind example
- function object研究之十九 bind
- function object研究之二
- function object研究之三
- function object研究之四
- function object研究之五
- function object研究之九 visit_each
- function object研究之八 add_value_*
- function object研究之七 is_placeholder
- function object研究之十 storageN
- function object研究之十一 addressof
- function object研究之十二 reference_wrapper
- function object研究之十三 result_traits
- function object研究之十四 unwrap
- function object研究之十五 list1分析
- function object研究之十六 listN分析
- function object研究之十七 list_av_N
- function object研究之十八 bind_t
- PowerShell 瑞士军刀升级版
- 电路积累
- 【8090在职场】个人提升方法三部曲:行动,记录、总结 (作者:warfalcon)
- j2EE 之 jsp阶段总结
- POJ2454:Jersey Politics(贪心+随机化)
- function object研究之六 bind example
- j2EE 之 xml
- 游戏服务器框架
- Spring Batch 2.1.8 中文文档(八)
- 【8090在职场】写博客是一种「写作式学习」
- 注册CSDN以来第一篇博文
- 数学黑洞(二)任何数都逃不出的西西弗斯黑洞
- 设置对话框显示位置
- select * from dual (转)