I want to create an array mapping integer values to member functions so that
(this->*actionMap[i])();
executes the method. In order to populate the array, I would like a method that sets elements of the array to the corresponding action.
I saw in an earlier question that it should use std::function and std::bind but I am not following the syntax, and I do not understand how to declare the array: How to properly pass member function as a parameter
Here is the M(non)WE Note that I want a base class to be able to execute methods on the derived object.
#include <iostream>
using namespace std;
class Base;
typedef void (Base::*Action)();
class Base {
Action actions[3];
public:
void setAction(int a, Action act) {
actions[a] = act;
}
void f() { cout << "f"; }
void go() {
for (int i = 0; i < 3; i++)
(this->*actions[i])();
}
};
struct Derived : public Base {
void g() { cout << "g"; }
void h() { cout << "h"; }
Derived() {
setAction(1, f);
setAction(2, g);
setAction(1, h);
}
};
int main() {
Derived d;
d.go();
}