interfunction switch

Started by
1 comment, last by mrbastard 15 years, 7 months ago
I have a class which i inherit from multiple helper class. These helpers holds functions and member for events. Now in the main event function (call msg). it has a switch and has tons of cases. The problem is i like to add the newly supported events inhered from the helper class. How should i do this? The options i see are to use a define/macro to insert the helper class event cases to the switch. or i could have a bunch of ifs that call the helper functions which will check if it handled the event and do it if it can. defines/macros are asking for trouble many ifs with helper subfunc can hide event collision (i would know if i handle a case twice with macros) what should i do and how else can i handle this? [Edited by - AcidZombie24 on September 18, 2008 5:51:23 AM]
<SkilletAudio> Your framerate proves your lack of manhood
Advertisement
If I understand your post:

class A{public:   virtual void msg();};void A::msg(){    switch(x)       {       case a: blah; break;       case b: blah; break;       }}class B : public A{public:    virtual void msg();};void B::msg(){    switch(x)       {       case c: blah; break;       case d: blah; break;       default: A::msg();       }}


Any case not handled by B is passed on to A's msg function.

Or, if you want it the other way round, and A gets the first chance to handle the message:

class A{public:   virtual bool msg();};bool A::msg(){    switch(x)       {       case a: blah; break;       case b: blah; break;              default: return false;       }    return true;}class B : public A{public:    virtual bool msg();};bool B::msg(){    if(A::msg()) return true;    switch(x)       {       case c: blah; break;       case d: blah; break;       }    return true;}
As I understand it your problem is with the maintainance involved in adding new event types, is that correct?

EasilyConfused's solution is great if things remain that simple, but add more classes or branch the inheritance hierachy and suddenly you have a load of problems - the concrete leaf classes can only dispatch to their own bases (as in EasilyConfused's example), and the bases can only really dispatch to the actual concrete class (using the old Base::event() calls Concrete::doEvent() trick).

One more general solution (but one that comes with it's own associated problems) is double dispatch. I recommend reading around the topic a bit though - it may be in your situation you don't need a fully general solution so you'll probably pick up some interesting ideas from any discussion of double dispatch. "Modern C++ Design" has a great discussion of the issues involved and how Loki solves them (though that may go into more dpeth than you need).

I grew up in shirland. Small world, eh [smile]
[size="1"]

This topic is closed to new replies.

Advertisement