boost::绑定具有默认值的成员函数


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)();失败并出现编译错误: 错误:非静态成员函数的使用无效

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

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

尝试:

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

问题是,当您通过bind()调用该函数时,编译器不知道该绑定函数存在默认参数值,因此会给您错误,因为您没有必需的参数

最新更新