ITeye博客

boost::bind使用例子

kingoal · 2009-04-11 22:32 · C++ · Markdown

#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
#include <iterator>

#include <boost/bind.hpp>

using namespace std;

void composite1()
{
    list<double> l;

    l.push_back(1.0);
    l.push_back(10.0);
    l.push_back(100.0);
    l.push_back(1000.0);

    cout<<"Before transformation"<<endl;
    copy(l.begin(),l.end(),ostream_iterator<double>(cout,"\t"));
    cout<<endl;

    transform(
        l.begin(),
        l.end(),
        l.begin(),
        boost::bind(
            multiplies<double>(), 0.9,
            boost::bind(
                multiplies<double>(),_1,1.10)
                )
        );

    cout<<"After transformation"<<endl;
    copy(l.begin(), l.end(),ostream_iterator<double>(cout,"\t"));
    cout<<endl;
}

void composite2()
{
    vector<int> iVec;

    iVec.push_back(5);
    iVec.push_back(10);
    iVec.push_back(2);
    iVec.push_back(6);
    iVec.push_back(8);
    iVec.push_back(7);

    int count = count_if(
        iVec.begin(),
        iVec.end(),
        boost::bind(logical_and<bool>(),
                    boost::bind(greater<int>(),_1,5),
                    boost::bind(less_equal<int>(),_1,10)
                   )
        );

    cout<<"Count: "<<count<<endl;
}

class trace
{
public:
    trace() {cout<<"trace::trace()"<<endl;}

    trace(const trace & t)
    {
        cout<<"trace::trace(const trace& t)"<<endl;
    }

    trace& operator=(const trace& other)
    {
        cout<<"trace::operator=(const trace& other)"<<endl;
        return *this;
    }

    ~trace()
    {
        cout<<"trace::~trace()"<<endl;
    }

    void print(string name) const
    {
        cout<<"String: "<<name<<endl;
    }
};

class Base
{
public:
    virtual void print()
    {
        cout<<"I am Base::print()"<<endl;
    }
};

class Derived: public Base
{
public:
    void print()
    {
        cout<<"I am Derived::print()"<<endl;
    }
};

int main(int argc,char* argv[])
{
    //composite2();
    //trace t;

    //boost::bind(&trace::print,boost::ref(t),_1)("kingoal");
    Derived d;
    Base b;

    boost::bind(&Base::print,boost::ref(b))();
    boost::bind(&Base::print,boost::ref(d))();

    return 0;
}

评论(1)

  1. #1 楼 · docong · 2010-10-19 23:41

    g++ bind.cpp -I$BOOST_ROOT -o mybind

    ls

    bind. mybind

    ./mybind

    I am Base::print() I am Derived::print()

评论功能维护中,当前仅展示历史评论。