boost bind 和 boost function學習

#include <iostream>

#include <boost/function.hpp>

#include <boost/bind.hpp>

using namespace std;


 

bool some_function(int a, int b)

{

    cout<<" a = " <<a << " b = " << b <<endl;

    return a < b;

}

 

class CFunctionCallA

{

public:

    CFunctionCallA(){}

    CFunctionCallA(int a_a, int a_b){m_a = a_a;m_b=a_b;}

    ~CFunctionCallA(){}

private:

    int m_a;

    int m_b;

public:

    bool output(int c, int d)

    {

        cout<<m_a<<m_b << c << d <<endl;

        return m_a<m_b;

    }

};

 

class CFunctionCallB

{

public:

    CFunctionCallB(){}

    CFunctionCallB(int a_a, int a_b){m_a = a_a;m_b=a_b;}

    ~CFunctionCallB(){}

private:

    int m_a;

    int m_b;

public:

    bool output(int c, int d)

    {

        cout<<m_a<<m_b << c << d <<endl;

        return m_a<m_b;

    }

};

 

void set_call(boost::function<bool (int ,int )> f)

{

    f(1,2);

}

 

int main()

{

    boost::function<bool (int ,int )> f_1;

    f_1 = &some_function;

    f_1(1,2);

    set_call(&some_function);

    

    /*----------------

        下面這兩個例子,展示瞭如何使用boost function、bind 來實現 基類多態的效果,兩個不同的類有相同參數和返回值的函數,

        但是這兩個類不是繼承自同一個類,通過如下方法達到像基類一樣統一調用的效果。

    -----------------*/

    CFunctionCallA l_func_obja(1,2);

    boost::function<bool (int, int)> f_2 = boost::bind(&CFunctionCallA::output, &l_func_obja,_1,_2);

    f_2(3,4);

    

    CFunctionCallB l_func_objb(5,6);

    boost::function<bool (int, int)> f_3 = boost::bind(&CFunctionCallB::output, &l_func_objb,_1,_2);

    f_3(7,8);

    return 0;

}

// g++ function.cpp -o function -lboost_system

運行結果:

./function
 a = 1 b = 2
 a = 1 b = 2
1234
5678

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章