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.


 



原创粉丝点击