Search code examples
c++c++11lambdastdstdbind

How to use std::bind with lambda


I am trying to use std::bind within my lambda:

#include <functional>
#include <iostream>
#include <string>

struct Foo {
    Foo() {}
    void func(std::string input)
    {
        std::cout << input << '\n';
    }

    void bind()
    {
        std::cout << "bind attempt" << '\n';
        auto f_sayHello = [this](std::string input) {std::bind(&Foo::func, this, input);};
        f_sayHello("say hello");
    }
};

int main()
{
    Foo foo;
    foo.bind();    
}

What I do expect when I run this code, is to see following output

bind attempt
say hello

But I do only see "bind attempt". I am pretty sure there is something I don't understand with lambda.


Solution

  • std::bind(&Foo::func, this, input);
    

    This calls std::bind, which creates a functor that calls this->func(input);. However, std::bind doesn't call this->func(input); itself.

    You could use

    auto f = std::bind(&Foo::func, this, input);
    f();
    

    or

    std::bind(&Foo::func, this, input)();
    

    but in this case why not just write it the simple way?

    this->func(input);