`
kingoal
  • 浏览: 156455 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

boost::bind基本应用

    博客分类:
  • C++
阅读更多

boost::bind功能强大,可以很好的实现对函数,函数对象之类的进行绑定

下面是一个具体的例子

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

#include <boost/bind.hpp>

using namespace std;

class Person
{
public:
    Person(string name)
    {
        name_ = name;
    }

    void doit()
    {
        cout<<"I am "<<name_<<endl;
    }
private:
    string name_;
};

int main(int argc,char* argv[])
{
    vector<Person> p;
    p.push_back(Person("Person A"));
    p.push_back(Person("Person B"));
    p.push_back(Person("Person C"));

    cout<<"Using the for loop "<<endl;
    for(vector<Person>::iterator iter = p.begin(); iter != p.end(); ++ iter)
    {
        iter->doit();
    }

    cout<<"Using for_each algorithm"<<endl;
    for_each(p.begin(), p.end(), mem_fun_ref(&Person::doit));

    cout<<"Using the bind function"<<endl;
    for_each(p.begin(), p.end(), boost::bind(&Person::doit, _1));

    return 0;
}

 三种方式实现的功能都是一样的,然而下面是其差别:

 

第一种方式的缺点是效率不是很高,因为其每一次都要计算p.end()

第二种方式就是适应性不是很强,对于非指针情况下使用mem_fun_ref,在于指针情况下使用men_fun,并且其不能够实现对智能指针之类的调用

所以推荐使用第三种方式,对不同类型的情况下调用方式都是一样的

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics