雖然重構了一些傳統的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");