【发布时间】:2010-09-08 12:54:32
【问题描述】:
在重构一些遗留 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" );
【问题讨论】:
标签: c++