Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C++ member function pointer from a struct

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?

like image 489
aaron Avatar asked Oct 15 '11 06:10

aaron


1 Answers

Use:

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

Tested and compiles ;)

like image 105
VoidStar Avatar answered Sep 22 '22 20:09

VoidStar