虽然重构了一些传统的C++代码,但我发现我可能会通过某种方式删除一些代码重复,从而定义一个变量,该变量可指向任何共享相同签名的类方法。一个小挖之后,我发现我可以做类似如下:指向C++类方法的指针
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;
}
};
我的问题是 - 这是正确的方式去吗?我应该考虑Boost必须提供的任何东西吗?
编辑...
好了,我的错 - 我要调用该方法,像这样:
bool res = ((*this).*CaseMethod)(999, "Hello World");