Your class must somehow remember which function pointer to use. Save it as a member of the class:
class Test { public: Test() : func(0) {} int operator()() { // Note that pointers to Test member functions need a pointer to Test to work. return (this->*func)(); // undefined behavior if func == 0 } void SetIt(int i) { if(i == 1) { func = &Test::DoIt1; } else { func = &Test::DoIt2; } } private: int DoIt1() { return 1; } int DoIt2() { return 2; } // Typedef of a pointer to a class method. typedef int (Test::*FuncPtr)(); FuncPtr func; };
However, before embarking on this, first profile your code and see if branching through switch
or if
is really a bottleneck (it may not be so!). Modern processors have very conflicting performance characteristics, so compilers can generate more efficient code than you think. The only way to make sure that forking is actually too expensive for you is to profile your code. (And by "profiling," I mean "run well-designed experiments," rather than "come up with a hunch without testing.")
source share