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
// conven开发者_开发百科ient.
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.
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.
here's what i have so far. it works ... but feels like an abomination. how could i improve it further? for instance, how to get rid of the reinterpret_cast?
@dimitri: thanks for the tip with the mutex, i'll add that.
class Observer {
public:
static Observer* instance()
{
if ( !mInstance )
mInstance = new Observer();
return mInstance;
}
virtual ~Observer() {}
template<typename ReturnType, typename Params>
sigc::signal<ReturnType, Params>* get( const std::string &id )
{
SignalMap::const_iterator it = mSignals.find( id );
if ( it == mSignals.end() )
return 0;
return reinterpret_cast<sigc::signal<ReturnType, Params>*>( (*it).second );
}
template<typename ReturnType, typename Params>
bool registerSignal( const std::string &id )
{
SignalMap::const_iterator it = mSignals.find( id );
if ( it != mSignals.end() ) {
// signal with the given id's already registered
return false;
}
// create a new signal instance here
sigc::signal<ReturnType, Params> *sig = new sigc::signal<ReturnType, Params>();
mSignals[ id ] = reinterpret_cast<sigc::signal<void>*>(sig);
return true;
}
private:
Observer()
{
}
SignalMap mSignals;
static Observer* mInstance;
};
Observer* Observer::mInstance = 0;
精彩评论