I would like to write a C#-like C++ event class like this :
template< typename ListenerType >
class Event
{
private:
std::vector< ListenerType * > m_aListeners;
public:
void operator += ( ListenerType * pListener )
{
m_aListeners.push_back( pListener );
}
void operator -= ( ListenerType * pListener )
{
std::vector< ListenerType * >::reverse_iterator revIter = m_aListeners.rbegin();
for( ; revIter != m_aListeners.rend(); ++revIter )
if( revIter == pListener )
{
m_aListeners.remove( revIter );
break;
}
}
};
class DataReceivedEvent : public Event< DataReceivedListener >
{
public:
void Trigger( const byte_t * pData )
{
for( size_t nI = 0; nI < m_aListeners.size(); ++nI )
m_aListeners[ nI ]->OnDataReceived( pData );
}
}
The problem is that it forces me to write a Trigger
method that always does the same thing (iterate and call handlers) for each event type since different events can have a different list of parameter, and for each event, the associated handler type has a mehod with a specific name.
I don't know much about C++11, but i have the feeling that it would be possible to avoid rewritting the Trigger method for each event type using templates. But i can't use C++11, so i wonder if there is a way, using older C++ version, to do that, in a type safe way.
EDIT : I thought about creating a hierarchy of event data classes, i.e template< typename ListenerType >::Data
and DataReceivedEvent::Data : public template< typename ListenerType >::Data
so that i can have a Trigger method always taking a single argument, i.e virtual void Trigger( const Data * pData )
. But I still have the problem that it needs to call a specific method in the event listener.