对于具有默认值的成员函数,使用boost :: bind?

时间:2012-06-07 12:32:02

标签: c++ boost bind

struct A
{
  A(int v):value(v){}
  int someFun(){return value;}
  int someOtherFun(int v=0){return v+value;}
  int value;
};

int main()
{
    boost::shared_ptr<A> a(new A(42));
    //boost::function<int()> b1(bind(&A::someOtherFun,a,_1)); //Error
    boost::function<int()> b2(bind(&A::someFun,a));
    b2();
    return 0;
}

bind(&A::someOtherFun,a)();因编译错误而失败:错误:无效使用非静态成员函数

如何绑定someOtherFun类似于someFun?即,它们应绑定到相同的boost :: function类型。

1 个答案:

答案 0 :(得分:2)

A::someFun()A::someOtherFun()有不同的类型:第一个不需要参数,第二个需要1(可以省略,编译器会为你插入defaqult值)

尝试:

bind(&A::someOtherFun, a, _1)(1);

问题是当你通过bind()调用函数时,编译器不知道该绑定函数有一个默认参数值,因此你没有所需参数就会出错

相关问题