简体   繁体   中英

How to call through a member function pointer?

I'm trying to do some testing with member function pointer. What is wrong with this code? The bigCat.*pcat(); statement doesn't compile.

class cat {
public:
   void walk() {
      printf("cat is walking \n");
   }
};

int main(){
   cat bigCat;
   void (cat::*pcat)();
   pcat = &cat::walk;
   bigCat.*pcat();
}

More parentheses are required:

(bigCat.*pcat)();
^            ^

The function call ( () ) has higher precedence than the pointer-to-member binding operator ( .* ). The unary operators have higher precedence than the binary operators.

Today, the canonical way is using the std::invoke function template, especially in generic code. Please note, that the member function pointer comes first:

import <functional>;

std::invoke(pcat, bigCat);

What you get: Unified calling syntax for virtually anything, that is invocable.

Overhead: none.

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