首页 > 代码库 > 1,Boost -> Bind

1,Boost -> Bind

#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>
using namespace std;
void dprint(int x,int y)
{
    cout << x << " " <<y <<endl;
}

class Bind_test
{
public:
    void setData(int x,int y)
    {
        _x = x;
        _y = y;
    }
    void printData()
    {
        cout << _x << " " <<_y <<endl;
    }
private:
    int _x;
    int _y;

};

void increnum(int &dg)
{
    dg++;
}

int main()
{
    boost::bind(&dprint,5,5)(); // 5,5
    boost::bind(&dprint,3,_1)(4);  // 3, 5
    boost::bind(&dprint,_1,_1)(2);  // 2, 2
    boost::bind(&dprint,_1,_2)(1,2);  // 1, 2
    boost::bind(&dprint,_2,_1)(1,2);  // 2, 1 ->函数参数对掉
    
    cout << "\nbind the class function\n";
    boost::shared_ptr<Bind_test> bclass(new Bind_test);
    boost::bind(&Bind_test::setData,bclass,1,2)();
    bclass->printData();

    Bind_test *bclass_02  = new Bind_test;
    boost::bind(&Bind_test::setData,bclass_02,2,3)();
    bclass_02->printData(); // 2 ,3
    delete  bclass_02;


    Bind_test bclass_03;
    boost::bind(&Bind_test::setData,&bclass_03,4,5)(); 
    bclass_03.printData(); // 4 ,5
    boost::bind(&Bind_test::setData,&bclass_03,_1,_1)(9); 
    bclass_03.printData(); // 9 ,9
    boost::bind(&Bind_test::setData,&bclass_03,_1,_2)(9,10); 
    bclass_03.printData(); // 9 ,10


    int dgNum = 0;
    boost::bind(&increnum,boost::ref(dgNum))(); // 类似C++11 Thread 里要传递引用std::ref(x)
    cout << dgNum <<endl;



    cin.get();
    return 0;
}

 

1,Boost -> Bind