Encapsulating boost::signal and boost::bind

579 Views Asked by At

I have a problem now. I am trying to encapsulatie boost::signal and boost::bind into my own Event class.

class MyEvent
{
private:
  boost::signal<void ()> Sig;
public:
  void Subscribe(.........)
  {
    Sig.connect(boost:bind(.........);
  }

  void Raise()
  {
    Sig();
  }
};

I have try to pass function pointer in the Subscribe function's signature and visual studio just gives me tones of errors. I dont know how to write the signature of Subscribe and What to pass into boost::bind, ideally I will have boost::bind(&MyClass::MyHandler, &MyClassObject) in Subscribe function and will Call it outside like MyEventObject.Subscribe(&MyClass::MyHandler, &MyClass). Can any people help me fill that two blanks?

1

There are 1 best solutions below

2
Igor R. On

You can just make Subscribe a template:

#include <boost/signals2.hpp>
#include <boost/bind.hpp>
class MyEvent
{
private:
  boost::signals2::signal<void ()> Sig;
public:
  template<class SlotClass> 
  void Subscribe(void (SlotClass::*func)(), SlotClass *obj)
  {
    Sig.connect(boost::bind(func, obj));
  }
  void Raise()
  {
    Sig();
  }
};

struct Test
{
  void f()
  {}
};

int main()
{
  MyEvent myEvent;
  Test test;
  myEvent.Subscribe(&Test::f, &test); // test must outlive myEvent!
}

Note however that such a wrapper limits its user very much: with original signal he could connect any callable of any kind created in various ways, while with your wrapper he must pass a pointer to member function and a pointer to object.