GoFaster
GoFaster

Reputation: 905

Using boost.signals2 how do I connect dynamically allocated objects to a signal

I have a class named Candidate containing a function named DataUpdate(). I intend to dynamically create many instances of Candidate and have each instance connect it's function DataUpdate() as a slot to a boost.signals2 signal; in readiness to receive signals.

The code I have developed below is giving the error:

Error 2 error C2276: '&' : illegal operation on bound member function expression

I'm unsure of the correct code to achieve the desired result. The problem seems to lie in in dereferencing the pointer candidateInstance to get the address of the instance's DataUpdate() function to pass to signal.connect(). Is anyone please able to advise the correct approach?

Candidate *candidateInstance;

//INSTANTIATE CANDIDATE INSTANCE
++DataStream::ID;//increment static variable
candidatesVector.push_back(candidateInstance = new Candidate(ID));

//CONNECT DATAUPDATE() OF CANDIDATE INSTANCE
signal.connect( &((*candidateInstance).DataUpdate) );

//FIRE SIGNAL
signal(BarNumber(), DateTime(), Open(), High(), Low(), Close());

Upvotes: 0

Views: 1307

Answers (1)

awesoon
awesoon

Reputation: 33671

You should use bind to create wrapper for member function.

#include <iostream>
#include <memory>
#include <functional>

#include <boost/signals2.hpp>

class Foo
{
public:
    void foo()
    {
        std::cout << "I'm foo() from Foo, this == " << this << std::endl;
    }
};

int main()
{
    auto foo_ptr = std::make_shared<Foo>();

    boost::signals2::signal<void()> sig;

    sig.connect(std::bind(&Foo::foo, foo_ptr));

    sig();

    return 0;
}

Upvotes: 2

Related Questions