1

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
peterphonic
  • 951
  • 1
  • 19
  • 38

1 Answers1

5
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);
user253751
  • 57,427
  • 7
  • 48
  • 90
  • I need to pass an std::function to a 3rdParty, that is why. So, I was playing around this new concept for me, trying to understand. Thx for the answer. – peterphonic Jan 18 '16 at 21:34