boost bind 和 boost function学习

本文介绍了如何使用Boost库中的bind和function来实现函数回调和模拟基类多态的效果。通过示例展示了如何将成员函数绑定到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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值