Blasco
Blasco

Reputation: 1745

Std bind equivalent to lambda for binding a member function to a std function

I can bind a private member function using a lambda. I'm struggling to write the equivalent using std::bind. This is my attempt, but it doesn't compile.

#include <functional>

class A { 
    private: 
        double foo(double x, double y); 
    public:          
        A(); 
        std::function<double(double,double)> std_function;      
 }; 

A::A() {
    // This works:
    //std_function = [this](double x, double y){return foo(x,y);};

    std_function = std::bind(&A::foo,this,std::placeholders::_1));
} 

Upvotes: 1

Views: 1265

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

std_function is supposed to take 2 parameters, but you're only specifying one. Note that the placeholders are used for arguments to be bound when std_function is invoked later.

Change it to

std_function = std::bind(&A::foo, this, std::placeholders::_1, std::placeholders::_2);

Upvotes: 2

Related Questions