boost::function使用

boost::function使用

1.全局非静态函数

int f(int a, int b)
{
    return a + b;
}
int main()
{
    boost::function<int(int,int)> func;
    assert(!func); 

    func = f; // 或者 func = &f;
    if (func)
    {
        cout<<func(10,20)<<endl;
    }

    func = 0;
    assert(func.empty());
}

2. 成员函数(Style_1)

struct demo_class
{
    int add(int a,int b)
    {
        return a + b;
    }
};
int main()
{
    demo_class sc;

    boost::function<int(demo_class&,int,int)> func = boost::bind(&demo_class::add,_1,_2,_3);
    cout<<func(sc,20,20)<<endl;
}

3. 成员函数(Style_2)
struct demo_class
{
    int add(int a,int b)
    {
        return a + b;
    }
};
int main()
{
    demo_class sc;

    boost::function<int(int,int)> func = boost::bind(&demo_class::add,&sc,_1,_2);
    cout<<func(30,20)<<endl;
}
4. 常量对象实例
struct demo_class
{
    int operator()(int x)const
    {
        return x * x;
    }
};
int main()
{
    demo_class sc;


    boost::function<int(int)> func = boost::cref(sc);//使用cref包装常量对象的引用,参看demo_class::operator(int x)const
    cout<<func3(10)<<endl;
}
5. 非常量对象实例
struct demo_class
{
    int operator()(int x)
    {
        return x * x;
    }
};
int main()
{
    demo_class sc;

    boost::function<int(int)> func = boost::ref(sc);//使用cref包装对象的引用,参看demo_class::operator(int x)
    cout<<func3(10)<<endl;
}
6. 对象实例(Style_2)
struct demo_class
{
    int operator()(int x)
    {
        return x * x;
    }
};
int main()
{
    demo_class sc;

    boost::function<int(int)> func = sc; // 这里将对象 sc 的一个拷贝 赋值给 func
    cout<<func3(10)<<endl; // 这里调用不是对象sc. 而是sc的一个拷贝
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值