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.

2
  • 1
    std::bind(&Foo::func, this, input)(); ? Commented Jan 18, 2016 at 20:21
  • @PiotrSkotnicki Wow, quick working answer. Thx Commented Jan 18, 2016 at 20:24

1 Answer 1

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

1 Comment

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.

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.