![](/img/trans.png)
[英]How to fill a function pointer member with class instance member function pointer?
[英]Pointer to member function of instance instead of class
當我根據某些條件獲得指向成員函數的指針然后調用該函數時,我有以下類。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.