This was a bit fiddly to get right. I got inspiration from How do I create and use an array of pointer-to-member-function?
Based on my post about Function pointers / function callbacks / function variables I modified it to work with class functions:
class foo {
public:
void doAction0 ()
{
Serial.println (0);
}
void doAction1 ()
{
Serial.println (1);
}
void doAction2 ()
{
Serial.println (2);
}
void doAction3 ()
{
Serial.println (3);
}
void doAction4 ()
{
Serial.println (4);
}
// typedef for class function
typedef void (foo::*GeneralFunction) ();
// array of function pointers
GeneralFunction doActionsArray [5] =
{
&foo::doAction0,
&foo::doAction1,
&foo::doAction2,
&foo::doAction3,
&foo::doAction4,
};
}; // end of class foo
void setup ()
{
Serial.begin (115200);
Serial.println ();
Serial.println (F("Starting"));
// test instance of foo
foo bar;
for (int i = 0; i < 5; i++)
{
// get member function pointer from array
foo::GeneralFunction f = bar.foo::doActionsArray [i];
// call the function
(bar.*f) ();
} // end of for loop
} // end of setup
void loop () { }
This compiles OK and prints:
Starting
0
1
2
3
4
Amended answer
I was wondering why you needed to specify bar
in this line above:
foo::GeneralFunction f = bar.foo::doActionsArray [i];
The reason is that the code above had the array as non-static, and thus a copy belonged to each instance of the class. This doesn't make a huge amount of sense, so the modified code below makes the array static
and const
. That is, the array should be the same for every instance of foo
and also never change.
Modified code below:
class foo {
public:
void doAction0 ()
{
Serial.println (0);
}
void doAction1 ()
{
Serial.println (1);
}
void doAction2 ()
{
Serial.println (2);
}
void doAction3 ()
{
Serial.println (3);
}
void doAction4 ()
{
Serial.println (4);
}
// typedef for class function
typedef void (foo::*GeneralFunction) ();
static const GeneralFunction doActionsArray [5];
}; // end of class foo
// array of function pointers
const foo::GeneralFunction foo::doActionsArray [5] =
{
&foo::doAction0,
&foo::doAction1,
&foo::doAction2,
&foo::doAction3,
&foo::doAction4,
};
void setup ()
{
Serial.begin (115200);
Serial.println ();
Serial.println (F("Starting"));
// test instance of foo
foo bar;
for (int i = 0; i < 5; i++)
{
// get member function pointer from array
foo::GeneralFunction f = foo::doActionsArray [i];
// call the function
(bar.*f) ();
}
} // end of setup
void loop () { }
This will also save RAM, as the array of function pointers only exists once, not once per instance of the class.