boost::function

// 忽略警告
#define _SCL_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <assert.h>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/ref.hpp>
#include <boost/assign/list_of.hpp>// list_of
using namespace boost;
using namespace std;
#include <algorithm>// for_each

int Plus(int a, int b)
{
    return a + b;
}

struct demo
{
    int add(int a, int b)
    {
        return a + b;
    }
    int operator()(int a) const
    {
        return a * a;
    }
};

template<typename T>
struct summary
{
    typedef void result_type;
    T sum;
    summary(T v = T()) :sum(v){}
    void operator()(T const &x)
    {
        sum += x;
        print(sum);
    }
    void print(T num){ cout << num * num << endl; }
};

// 用于回调
void call_back_print(int n)
{
    cout << n << endl;
}
class call_back
{
private:
    typedef boost::function<void(int)> Fun;
    Fun fun;// 到时候用single2代替
    int n;
public:
    call_back(int a) :n(a){}
    template<typename CallBack>
    void accept(CallBack cb)
    {
        fun = cb;// 绑定回调函数
    }
    void run()
    {
        fun(n);// 执行
    }
};

int main()
{
    boost::function<int(int, int)> fun(Plus);// fun(&Plus)也可以,存储函数Plus
    assert(fun);
    cout << fun(2, 4) << endl;

    fun = 0;// 等价fun.clear(); 清空function
    assert(!fun);
    try
    {
        fun(2, 4);
    }
    catch (boost::bad_function_call& e)
    {
        if (fun.empty())cout << "fun is empty!" << endl;// fun is empty!
        cout << e.what() << endl;// call to empty boost::function
    }

    boost::function<int(demo&, int, int)> fun1 = boost::bind(&demo::add, _1, _2, _3);// 函数声明时指定绑定类型 和 函数
    cout << fun1(demo(), 4, 5) << endl;// 9

    demo d;
    boost::function<int(int, int)> fun2 = boost::bind(&demo::add, &d, _1, _2);// 在bind时绑定demo的实例 和 函数
    cout << fun2(4, 5) << endl;// 9

    // 引用
    boost::function<int(int)> fun3 = boost::cref(d);// 包装对象的引用
    cout << fun3(10) << endl;// 100

    vector<int> v = (assign::list_of(1), 2, 3, 4, 5, 6, 7, 8, 9, 10);
    summary<int> s;
    boost::function<void(int const&)> fun4(boost::ref(s));
    for_each(v.begin(), v.end(), fun4);// std 1^2 (1+2)^2  (1+2+3)^2 ...
    cout << s.sum << endl;// 55


    // 回调
    call_back cb(100);
    cb.accept(call_back_print);// 绑定
    cb.run();// 100

    cb.accept(boost::bind(&summary<int>::print,s,_1));// 绑定
    cb.run();// 10000

    cb.accept(boost::ref(s));// sum = 55
    cb.run();// (55 +100)^2
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值