Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following:
class MyClass { protected: bool CaseMethod1( int abc, const std::string& str ) { cout << 'case 1:' << str; return true; } bool CaseMethod2( int abc, const std::string& str ) { cout << 'case 2:' << str; return true; } bool CaseMethod3( int abc, const std::string& str ) { cout << 'case 3:' << str; return true; } public: bool TestSwitch( int num ) { bool ( MyClass::*CaseMethod )( int, const std::string& ); switch ( num ) { case 1: CaseMethod = &MyClass::CaseMethod1; break; case 2: CaseMethod = &MyClass::CaseMethod2; break; case 3: CaseMethod = &MyClass::CaseMethod3; break; } ... bool res = CaseMethod( 999, 'hello world' ); ... reurn res; } };
My question is – is this the correct way to go about this? Should I consider anything that Boost has to offer?
Edit…
Ok, my mistake – I should be calling the method like so:
bool res = ( (*this).*CaseMethod )( 999, 'Hello World' );
What you have there is a pointer-to-member-function. It will solve your problem. I am surprised that your ‘TestSwitch’ function compiles, as the calling syntax is slightly different to what you might expect. It should be:
However, you might find a combination of boost::function and boost::bind makes things a little easier, as you can avoid the bizarre calling syntax.
Of course, this will bind it to the current
thispointer: you can make thethispointer of the member function an explicit third parameter if you like:Another alternative might be to use virtual functions and derived classes, but that might require major changes to your code.