Search code examples
c++boostboost-signals

Pass boost::signal as boost::function


I have a class with signal member encapsulated with boost::function.

Is it possible to add another signal as a handler with this API?

class Foo
{
public:
  VOID AddHandler(boost::function<VOID()> handler)
  {
     m_signal.connect(handler);
  }

private:
  boost::signal<VOID()> m_signal;
};

boost::signal<VOID()> signal;

VOID SignalCaller()
{
    signal();
}

int main( )
{ 
   Foo foo;
   //foo.AddHandler(signal); // I want to
   foo.AddHandler(&SignalCaller); // I have to
}

Solution

  • use the type "slot_type" that is declared inside your signal type

    class Foo
    {
    public:
        typedef boost::signal0<void> Signal;
        typedef Signal::slot_type Slot;
    
        //allowed any handler type which is convertible to Slot
        void AddHandler(Slot handler)
        {
            m_signal.connect(handler);
        }
    private:
      Signal m_signal;
    };
    
    void f()
    {
        std::cout << "f() called";
    }
    
    //usage
        Foo foo;
        foo.AddHandler(signal);
        foo.AddHandler(&f);