0

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());
awesoon
  • 32,469
  • 11
  • 74
  • 99
GoFaster
  • 835
  • 1
  • 12
  • 23

1 Answers1

2

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;
}
awesoon
  • 32,469
  • 11
  • 74
  • 99
  • So I tried using the format you suggested but this line; signal.connect(std::bind(std::mem_fn(&Candidate::DataUpdate), candidateInstance.get())); gives the error; Error C2064: term does not evaluate to a function taking 6 arguments. Any thoughts on how to fix it? Thanks. @soon – GoFaster May 13 '13 at 16:38
  • Looks like your function has more arguments than function represented in my answer. In this case you should use [placeholders](http://en.cppreference.com/w/cpp/utility/functional/placeholders). – awesoon May 13 '13 at 16:44
  • `bind` doesn't require `mem_fn` and can be bound to `shared_ptr`: `bind(&Foo::foo, foo_ptr);` – Igor R. May 13 '13 at 17:48
  • @soon Thanks for putting me on the right track, got code to compile and run like so: `//INSTANTIATE CANDIDATE INSTANCE ++DataStream::ID;//increment static variable to give unique ID no. Candidate* candidateInstance = new Candidate(ID, iDataNumber); //CONNECT DATAUPDATE() OF CANDIDATE INSTANCE signal.connect(bind(&Candidate::DataUpdate, candidateInstance, _1, _2, _3, _4, _5, _6, _7)); //FIRE SIGNAL signal(iDataNumber, BarNumber(), DateTime(), Open(), High(), Low(), Close());` – GoFaster May 14 '13 at 16:23