Avoiding duplication of code with static polymorphism

I have such an interface (except for much more than in the real library code)

struct IFoo { virtual void onA(A& a) = 0; virtual void onB(A& a) = 0; virtual void onC(A& a) = 0; }; 

and for me various listening to IFoo . Because of this, I developed a helper class similar to this:

 template <class T> struct IFooHelper { virtual void onA(A& a) { static_cast<T*>(this)->onGeneric(a); } virtual void onB(B& b) { static_cast<T*>(this)->onGeneric(b); } virtual void onC(C& c) { static_cast<T*>(this)->onGeneric(c); } }; 

so now that I have a lot of common behavior in the listener, instead of providing a virtual override for each individual IFoo function, I can do something like:

 struct Fox : public IFooHelper<Fox> { template <class T> void onGeneric(T& t) { //do something general } void onD(D& d) { //special behavior only for a type D } }; 

This worked fantastically well, but now I implement a listener for which I want some kind of general behavior, and then update the counter, say what type of call. In other words, assuming that I only have types A,B,C , as indicated above, my listener will:

 struct Ugly : public IFooHelper<Ugly> { void onA(A& a) { //8 lines of common code; //update some counter for type A objs; } void onB(B& b) { //8 lines of common code; //update some counter for type B objs; } void onC(C& c) { //8 lines of common code; //update some counter for type C objs; } }; 

In this case, the calls should be very fast (so without searching), and ideally I can use IFooHelper to summarize the general behavior in the template method, and then somehow it will still be able to distinguish between types, I was thinking about something like a specialized template structure with offsets to the static cons char * .. array or with char * values ​​themselves depending on T .. is there a better way?

+4
source share
1 answer

Not sure if I fully understand what you are looking for, but I will give him a chance. As a first step, consider the following:

 struct NotSoUgly : public IFooHelper<NotSoUgly> { void updateCounter(A& a) { //update some counter for type A objs; } void updateCounter(B& b) { //update some counter for type B objs; } void updateCounter(C& c) { //update some counter for type C objs; } template <class T> void onGeneric(T& t) { //8 lines of common code; updateCounter(t); } }; 

Further improvements are possible if you show us the contents of the updateCounter() methods so that we can come up with one common implementation for this, but without seeing the code, it's hard to guess.

+1
source

All Articles