6

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

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 those parenthesis around results in syntax errors recommending using .* or ->* neither of which work in this situation. Does anyone know the proper syntax?

aaron
  • 83
  • 2
  • 5
  • http://stackoverflow.com/questions/990625/c-function-pointer-class-member-to-non-static-member-function seems related to this question. – Rudi Oct 15 '11 at 06:47

2 Answers2

9

Use:

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

Tested and compiles ;)

Mankarse
  • 38,538
  • 10
  • 94
  • 140
VoidStar
  • 4,926
  • 26
  • 43
5

I haven't compiled any code, but just from looking at it I can see you're missing a few things.

  • Remove the MyClass:: from where you call the function pointer.
  • Need to pass the this pointer to the functions (if they use any instance data), so that means you need an instance of MyClass to call it.

(After a bit of research) It looks like you need to do something like this (also thanks to @VoidStar):

(this->*(functionMap[0].command)(x, y));
Daemin
  • 9,927
  • 4
  • 37
  • 44
  • Thanks for the explanation. The below answer works (with the parenthesis including 'this' instead of 'functionMap'. Thank you for the response. – aaron Oct 15 '11 at 07:15
  • I wasn't sure exactly if it required those or not. Though for that problem I would probably try a different solution, such as just using an if, or if more flexibility is required some sort of Command pattern. – Daemin Oct 15 '11 at 07:18