简体   繁体   中英

How can I make an array of method pointers?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM