0

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?

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
cynric4sure
  • 189
  • 1
  • 12

1 Answers1

0

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.

Igor R.
  • 14,716
  • 2
  • 49
  • 83
  • Thank you Igor. My boss ask me to encapsulate it so that avoid boost lib everywhere. I really want to expose it as it is more flexible to use boost::signal – cynric4sure May 06 '13 at 13:43
  • @cynric4sure You mean you're required to eliminate boost from the interfaces? Then, pay attention to the following points: 1) you class still exposes `boost::signals` in its definition (although it's `private`) and thus user's code would depend on boost headers. You might want hide it by means of pImpl; 2) You don't have to limit the user with pointer to member function! Instead, accept any callable and let the user to create it with `std::bind` or what ever he wants. – Igor R. May 06 '13 at 14:22