Search code examples
c++c++11stdbind

std::bind in constructor to callback method in class


I have a class Foo which is instanciated in class Bar.

I need to assign the callback of m_foo to the method of Bar called xpto(). I should be able to use the std::bind here, correct? What is wrong with my code?

The class Foo:

class Foo
{
public:
   Foo(std::function<void()> cb);
}

The class Bar:

class Bar
{
public:
   Bar(std::function<void()> cb);

   void xpto();
private:
   Foo m_foo;
}

Bar::Bar(std::function<void()> cb)
: m_foo(std::bind(&xpto)) // ERROR!!!?
{}

Solution

  • You're a little off in your use of bind():

    class Bar
    {
    public:
       Bar(std::function<void()> cb);
    
       void xpto();
    private:
       Foo m_foo;
    }
    
    Bar::Bar(std::function<void()> cb)
    : m_foo(std::bind(&Bar::xpto, this)
    {}
    

    That should work. I'm not sure why you have the cb argument to the constructor of Bar though.