I want to create an array of pointers to methods, so I can quickly select a method to call, based on a integer. But I am struggling a little with the syntax.
What I have now is this:
class Foo {
private:
void method1();
void method2();
void method3();
void(Foo::*display_functions[3])() = {
Foo::method1,
Foo::method2,
Foo::method3
};
};
But I get the following error message:
[bf@localhost method]$ make test
g test.cpp -o test
test.cpp:11:9: error: cannot convert ‘Foo::method1’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
11 | };
| ^
test.cpp:11:9: error: cannot convert ‘Foo::method2’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
test.cpp:11:9: error: cannot convert ‘Foo::method3’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
make: *** [<builtin>: test] Error 1
CodePudding user response:
Yes, you can, you just need to take the address of them:
void(Foo::*display_functions[3])() = {
&Foo::method1,
&Foo::method2,
&Foo::method3
};
... however, it's likely better if you have virtual
methods for an interface or a simple method that calls them all for a multi-method pattern.
CodePudding user response:
You can use typedef
for the type of pointer to your methods, and then store your methods in a std::array
holding that type:
class Foo {
private:
void method1() {};
void method2() {};
void method3() {};
typedef void (Foo::* FooMemFn)();
std::array<FooMemFn,3> display_functions = {
&Foo::method1,
&Foo::method2,
&Foo::method3
};
};
Instead of typedef
you can also use a using
statement:
using FooMemFn = void (Foo::*)();
Note that you must use operator&
with a class method to obtain a pointer-to-method.
A side note: consider to make display_functions
static if it will not change between various class instances.