Search code examples
c++callbackstdstdbind

No suitable conversion user-defined conversion with std::bind()


I'm trying to implement a Button class which invokes a callback when the button is clicked.

class Button
{
  public:
    void SetOnMouseClickCallback(std::function<void()> f);
  // Some other stuff
  private:
    std::function<void()> callback;
};
using ButtonPtr = std::unique_ptr< Button >;

void Button::SetOnMouseClickCallback(std::function<void()> f)
{
    callback = f;
}

In my App class I want to initialize all of my buttons and eventually assign a callback to them:

void App::Initialize()
{
    ButtonPtr b = std::make_unique<Button>(100.f, 100.f, 200.f, 50.f, "texture.jpg");
    b->SetOnMouseClickCallback(std::bind(&Foo)); // Error here under std::bind
}

void App::Foo()
{
    cout<<"bar";
}

I've been stuck here for the entire day and I have no clue anymore. Hope you can help me. Thanks in advance.


Solution

  • Foo is not a void(). You forgot to bind it to the current instance:

    std::bind(&App::Foo, this)