[英]Calling pointer-to-member function in call for a function passed to a template function
[英]How to call through pointer-to-member function saved in a container?
我正在嘗試編寫一個成員 function 依次調用同一 object 的其他成員函數,直到其中一個工作。
我想這樣寫:
class myClass
{
bool A() { return false; }
bool B() { return false; }
bool C() { return false; }
bool D() { return false; }
void doIt()
{
const QList<bool (myClass::*) ()> funcs({
&myClass::A, &myClass::B, &myClass::C, &myClass::D
});
bool result(false);
for (auto iter = funcs.cbegin(); !result && iter != funcs.cend(); ++iter)
{
result = this->(*iter) ();
}
}
};
但是我無法正確地通過迭代器調用我的 function 的語法。 qt-creator 顯示錯誤
called object type 'bool (myClass::*)()' is not a function or function pointer
指向第二個左括號,g++ 報告
must use .* or ->* to call pointer-to-member function
指向第二個右括號,兩者都在我分配的行中,導致 DoIt 成員 function。 (請注意,g++ 錯誤消息中的示例運算符包含在重音符號中,但如果我包含它們,標記會刪除“*”。)
我可以找到許多關於如何通過指向成員函數的指針進行調用的示例,但是這種將指向成員函數的指針保存在集合中並在this
調用中的組合沒有
由於()
運算符的優先級綁定,您需要添加更多括號:
result = (this->*(*iter))();
除了@1201ProgramAlar m 的答案,如果您可以訪問c++17編譯器,您可以通過使用來自<functional>
header 的std::invoke
來避免奇怪的語法。
#include <functional> // std::invoke
result = std::invoke(*iter, this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.