Search code examples
c++eventsclasslibsigc++

how to write a wrapper class for sigc++?


would like to have a central place to register new signals, connect to signals, and so on. now i thought to use sigc++. however, i don't know how to code a wrapper class for this template based lib. something along the lines of:

class EventManager {
public:
    ... singleton stuff ...
    template<typename ReturnType, typename Params>
    bool registerNewSignal( std::string &id )
    {
        sigc::signal<ReturnType, Params> *sig = new sigc::signal<ReturnType, Params>();

        // put the new sig into a map
        mSignals[ id ] = sig;
    }

    // this one should probably be a template as well. not very
    // convenient.
    template<typename ReturnType, typename Params>
    void emit( id, <paramlist> )
    {
        sigc::signal<ReturnType, Params> *sig = mSignals[ id ];
        sig->emit( <paramlist> );
    }

private:
    std::map<const std::string, ???> mSignals;
};

what should i replace the ??? with to make the map generic, but still be able to retrieve the according signal to the given id, and emit the signal with the given paramlist -- which i don't know how to handle either.


Solution

  • You'll need a base class which have emit() function:

    template<class Ret>
    class SigBase {
    public:
      virtual Ret emit()=0;
    };
    

    and then some implementation of it:

    template<class Ret, class Param1>
    class SigDerived : public SigBase<Ret>
    { 
    public:
      SigDerived(sigc::signal<Ret, Param1> *m, Param1 p) : m(m), p(p){ }
      Ret emit() { return m->emit(p); }
    private:
      sigc::signal<Ret, Param1> *m;
      Param1 p;
    };
    

    Then the map is just pointer to base class:

    std::map<std::string, SigBase<Ret> *> mymap;
    

    EDIT: It might be better if the SigBase doesn't have the Ret value, but instead only supports void returns.