简体   繁体   中英

How to call through pointer-to-member function saved in a container?

I am trying to write a member function that calls other member functions of the same object in turn until one of them works.

I would like to write this as below:

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) ();
      }
   }
};

But I can not get the syntax right to call my function through the iterator. qt-creator displays the error

called object type 'bool (myClass::*)()' is not a function or function pointer

pointing to the second opening bracket, and g++ reports

must use .* or ->* to call pointer-to-member function

pointing to the second close bracket, both in the line where I assign to result in the DoIt member function. (Note that the example operators in the g++ error message are enclosed within grave accents, but the markup drops the "*" if I include them.)

I can find any number of examples of how to call through pointers to member functions, but nothing with this combination of saving the pointers-to-member-function in a collection and calling in this

Because of the priority binding for the () operator, you need to add some more parens:

result = (this->*(*iter))();

In addition to the @1201ProgramAlar m 's answer, if you have access to the compiler, you could able to avoid the weird syntax, by using the std::invoke from <functional> header.

#include <functional> // std::invoke

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM