1

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));
} 

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

6 Comments

ahhh, I got it wrong I thought the placeholder meant to bind this to the first argument. Ok, great! thank you very much!
I feel bad I spent so much time in such a simple mistake.
@WooWapDaBug It's not bad if it helps you clarify the usage about placeholders.
Note using lambdas is almost always just a better choice
@PasserBy I think the same way, I was actually explaining this to someone and I wanted to show this person how uglier it looked with bind, but I couldn't make it work with bind because I always use a lambda. It was for the sake of an example
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.