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" );