boost::bind for a member function with default val

2019-06-02 20:32发布

问题:

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)(); fails with compile error: error: invalid use of non-static member function

How to bind someOtherFun similar to the someFun? i.e, they should bind to the same boost::function type.

回答1:

A::someFun() and A::someOtherFun() have different types: the first expects no parameters, the second expects 1 (which can be ommitted and the compiler inserts the defaqult value for you)

Try:

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

The problem is that when you call the function via bind(), the compiler does not know there is a default parameter value for that bound function and thus gives you error because you don't have the required parameter



标签: c++ boost bind