指向实例成员函数而不是类的指针
当我根据某些条件获得指向成员函数的指针然后调用该函数时,我有以下类。
class Test
{
public:
bool isChar(char ch) { return (ch >= 'a' && ch <= 'z'); }
bool isNumeric(char ch) { return (ch >= '0' && ch <= '0'); }
enum class TestType
{
Undefined,
Char,
Numeric,
AnotherOne,
};
bool TestFor(TestType type, char ch)
{
typedef bool (Test::*fptr)(char);
fptr f = nullptr;
switch(type)
{
case TestType::Char:
f = &Test::isChar;
break;
case TestType::Numeric:
f = &Test::isNumeric;
break;
default: break;
}
if(f != nullptr)
{
return (this->*f)(ch);
}
return false;
}
};
但实际上我不喜欢这种语法。有没有办法更换
(this->*f)(ch)
和
f(ch)
?
在我的实际代码中,函数足够大,但不清楚是什么(this->*f)。我正在寻找一些c++11解决方案。我知道std::function,如果找不到解决方案,我会使用它。
更新
我决定使用的解决方案,如果突然有人需要它:(感谢@StoryTeller - Unslander Monica)
bool TestFor(TestType type, char ch)
{
bool(Test::* fptr)(char) = nullptr;
switch(type)
{
case TestType::Char:
fptr = &Test::isChar;
break;
case TestType::Numeric:
fptr = &Test::isNumeric;
break;
default: break;
}
if(fptr != nullptr)
{
auto caller = std::mem_fn(fptr);
return caller(this, ch);
}
return false;
}
回答
如果语法让您如此烦恼,您总是可以使用std::mem_fn为成员函数生成一个廉价的一次性包装器。
auto caller = std::mem_fn(f);
caller(this, ch);