Search code examples
c++boostboost-bindboost-phoenix

Boost binding with member functions/variables


Class A has access to class B.

In a class B function, I'd like to call a function defined in class A, and pass to it arguments from class B.

So in class A I try to write the following to provide the desired function to class B.

A::provideFunction
{
    boost::function<void()> f = boost::bind(&A::Foo,this,boost::ref(&B::_param1,B::instance()),boost::ref(&B::_param2,B::instance())));
    B::instance()->provideFunction(f);
}

In class B, I just call the function:

B::callFunction()
{
    _param1 = "A";
    _param2 = "B";
    _f();
}

The problem I have is that boost:ref expects only 1 argument... what can I do to resolve this issu?


Solution

  • To get a pointer to data member, you don't do &T::foo, just do &obj->foo. To get a reference wrapper, ref(obj->foo).

    B* b = B::instance();
    boost::function<void()> f = boost::bind(
        &A::Foo, this, boost::ref(b->_param1), boost::ref(b->_param2)
    );
    b->provideFunction(f);
    

    Also, rethink your design — neither singletons nor this weird hidden implicit arguments thing are good.