簡體   English   中英

如何通過保存在容器中的成員指針 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 的答案,如果您可以訪問編譯器,您可以通過使用來自<functional> header 的std::invoke來避免奇怪的語法。

#include <functional> // std::invoke

result = std::invoke(*iter, this);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM