如何解决指向实例成员函数的指针而不是类
当我根据某些条件获得指向成员函数的指针然后调用该函数时,我有以下类。
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)
?
在我的实际代码中,函数 a 足够大,但不太清楚 (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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。