waas1919
waas1919

Reputation: 2595

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!!!?
{}

Upvotes: 0

Views: 1575

Answers (1)

Jason R
Jason R

Reputation: 11696

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.

Upvotes: 4

Related Questions