Search code examples
c++c++11smart-pointersstdbind

How to std::bind a smart pointer return method?


So I have this method inside my Bar class:

std::shared_ptr<sf::Sprite> Bar::getStuff() const
{
   //...
}

And I have my callback typedef:

typedef std::function<void()> Callback;

void Foo::registerCallback(const Callback& callback)
{
    //...
}

And now I want to use std::bind on this method, like:

Foo foo;
Bar bar; //I create an instance of an Bar, called bar. 

foo.registerCallback(std::bind(&Bar::getStuff, std::ref(bar))); //<--- ERROR!!!!

ERROR:

error C2562: 'std::_Callable_obj<std::_Bind<true,std::shared_ptr<sf::Sprite>,std::_Pmf_wrap<std::shared_ptr<sf::Sprite> (__thiscall Bar::* )(void) 

If I want to use a void method, it's ok. But I need to use the getStuff() method, which will return me a smart pointer to a sf::Sprite thing.

How can I achieve this?


Solution

  • Given you are using c++11, why not a lambda?

    foo.registerCallback([&bar]() { bar.getStuff(); });