I'm trying to write a template event class and keep as much code as possible inside this base class. I'm using the curiously recurring template pattern, but i'm not exactly sure about what i'm doing here.
template< class EventType >
class Event
{
protected:
std::vector< EventType::Listener * > m_aListeners;
public:
void operator += ( EventType::Listener * pListener )
{
m_aListeners.push_back( pListener );
}
void operator -= ( EventType::Listener * pListener )
{
std::vector< EventType::Listener * >::reverse_iterator revIter = m_aListeners.rbegin();
for( ; revIter != m_aListeners.rend(); ++revIter )
if( revIter == pListener )
{
m_aListeners.remove( revIter );
break;
}
}
void Trigger( EventType::Data * pData )
{
std::vector< EventType::Listener * >::iterator iter = m_aListeners.begin();
for( ; iter != m_aListeners.end(); ++iter )
CallListenert( iter, pData );
}
virtual void CallListener( EventType::Listener * pListener, EventType::Data * pData ) = 0;
};
And its subclass for a given event type :
class ConnectionSuccessEvent : public Event< ConnectionSuccessEvent >
{
public:
class Data
{
public:
Data( int iVal ) : m_iVal( iVal ) { }
public:
const int m_iVal;
};
class Listener
{
public:
virtual ~Listener() { }
virtual void OnConnectionSuccess( Data * pEventData ) = 0;
};
void CallListener( Listener * pListener, Data * pData )
{
pListener->OnConnectionSuccess( pData );
}
};
And a class implementing the listener class :
class MyClass : public ConnectionSuccessEvent::Listener
{
public:
void OnConnectionSuccess( ConnectionSuccessEvent::Data * pEventData )
{
std::cout << "OnConnectionSuccess : " << pEventData->m_iVal << std::endl;
}
};
Which i use as follows :
MyClass oMyClassInstance;
ConnectionSuccessEvent oOnConnectionSuccess;
oOnConnectionSuccess += & oMyClassInstance;
oOnConnectionSuccess += & oMyClassInstance;
ConnectionSuccessEvent::Data oData( 456 );
oOnConnectionSuccess.Trigger( & oData );
oOnConnectionSuccess -= & oMyClassInstance;
oOnConnectionSuccess -= & oMyClassInstance;
This is resulting in several compilations errors, the first one being :
Error 2 error C2059: syntax error : '>' c:\dev\eventtest\event.h 16
Which corresponds to the declaration of the vector m_aListeners.
I have two questions :
What is causing my error ? Am I not allowed to use EventType::Listener in my class Event ?
How is the curiously recurring pattern possible ? I mean, to be defined, the derived class requires its parent class be defined. But since it's parent it's parent class requires it's template parameter class to be defined i.e it's base class), then it's a problem, because for one to be defined, it needs the other one to be defined first. This is like having an instance of A in class B, and an instance ob B in class A.
Thank you !
EDIT : I can't use C++11.