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) {
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?