C ++ function pointer call from structure

I found information about calling C ++ function pointers and call pointers in structs, but I need to call a pointer to a member function that exists inside the structure, and I could not get the syntax correctly. I have the following snippet inside a method in the MyClass class:

void MyClass::run() { struct { int (MyClass::*command)(int a, int b); int id; } functionMap[] = { {&MyClass::commandRead, 1}, {&MyClass::commandWrite, 2}, }; (functionMap[0].MyClass::*command)(x, y); } int MyClass::commandRead(int a, int b) { ... } int MyClass::commandWrite(int a, int b) { ... } 

This gives me:

 error: expected unqualified-id before '*' token error: 'command' was not declared in this scope (referring to the line '(functionMap[0].MyClass::*command)(x, y);') 

Moving these parentheses around the results in syntax errors recommending use. * or โ†’ * none of which work in this situation. Does anyone know the correct syntax?

+6
source share
2 answers

Using:

 (this->*functionMap[0].command)(x, y); 

Tested and compiled;)

+8
source

I did not compile any code, but just by looking at it, I see that you are missing a few things.

  • Remove MyClass:: from which you are calling the function pointer.
  • You must pass a this pointer to functions (if they use instance data), so that means you need an instance of MyClass to call it.

(After a little research) It sounds like you need to do something similar (also thanks to @VoidStar):

 (this->*(functionMap[0].command)(x, y)); 
+5
source

Source: https://habr.com/ru/post/899352/


All Articles