boost::function使用

来源:互联网 发布:山东省网络信息办公室 编辑:程序博客网 时间:2024/06/07 03:10

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