Hi,
I want to develop a an application based on independent "CustomModule" that all derived from a base class "BaseModule" and that can send different kind of "CustomEvent" (derived from a "BaseModule" class) to each other. Each Module just knows that it is connected to others "BaseModule" (i.e. it does not know the specific type of "CustomModule" they are).
So the problem is the following: How can I specialize the code of CustomModule depending on the CustomEvent type that it receives and in the same time keeping a generic interface communication between Modules ? A precision: this code have to be wrapped in Python. So I would like to avoid the use of template class otherwise it will quickly be a mess.
Here are a piece of code (it was difficult to do it shorter) that works but I do not like the EventTypeID/downcasting mechanism. Any better idea ?
#include <stdio.h>
class BaseEvent
{
public:
virtual int getEventTypeID() {return 0;};
};
class CustomEventType1: public BaseEvent
{
public:
virtual int getEventTypeID() {return 1;};
};
class CustomEventType2: public BaseEvent
{
public:
virtual int getEventTypeID() {return 2;};
};
class BaseModule
{
public:
void doSomething(BaseEvent* pEvent) {printf("BaseModule::doSomething function called\n");};
virtual void receiveEvent(BaseEvent* pEvent) {doSomething(pEvent);};
};
class CustomModuleType1:public BaseModule
{
public:
void doSomething(CustomEventType1* pEvent) {printf("CustomModuleType1::doSomething function called\n");};
virtual void receiveEvent(BaseEvent* pEvent)
{
if (pEvent->getEventTypeID() == 1) {
CustomEventType1* pCustomEventType1 = static_cast<CustomEventType1*>(pEvent);
doSomething(pCustomEventType1);
}
else {
printf("Wrong Event Type in CustomModuleType1::receiveEvent\n");
}
};
};
class CustomModuleType2:public BaseModule
{
public:
void doSomething(CustomEventType2* pEvent) {printf("CustomModuleType2::doSomething function called\n");};
virtual void receiveEvent(BaseEvent* pEvent)
{
if (pEvent->getEventTypeID() == 2) {
CustomEventType2* pCustomEventType2 = static_cast<CustomEventType2*>(pEvent);
doSomething(pCustomEventType2);
}
else {
printf("Wrong Event Type in CustomModuleType2::receiveEvent\n");
}
};
};
int main(int argc, char** argv)
{
CustomEventType1* pCustomEventType1 = new CustomEventType1();
CustomEventType2* pCustomEventType2 = new CustomEventType2();
BaseModule* arrModul[2];
arrModul[0] = new CustomModuleType1();
arrModul[1] = new CustomModuleType2();
arrModul[0]->receiveEvent(pCustomEventType1);
arrModul[0]->receiveEvent(pCustomEventType2);
arrModul[1]->receiveEvent(pCustomEventType1);
arrModul[1]->receiveEvent(pCustomEventType2);
return 0;
}
it returns:
CustomModuleType1::doSomething function called
Wrong Event Type in CustomModuleType1::receiveEvent
Wrong Event Type in CustomModuleType2::receiveEvent
CustomModuleType2::doSomething function called