c++pointer-to-membermember-functionsfunction-callclass-members

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


Solution

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

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