简体   繁体   中英

Vector of non-static void member pointer functions with this

In C++17, how do you create a vector of non-static member pointer functions with this and subsequently call the functions?

Example.hpp

class Example{
    public:
        Example();

        void function1();
        void function2();
};

Example.cpp (psuedocode)

Example::Example(){
    std::vector<void (*)()> vectorOfFunctions;
    vectorOfFunctions.push_back(&this->function1);
    vectorOfFunctions.push_back(&this->function2);

    vectorOfFunctions[0]();
    vectorOfFunctions[1]();
}

void Example::Function1(){
    std::cout << "Function 1" << std::endl;
}

void Example::Function2(){
    std::cout << "Function 2" << std::endl;
}

You can use std::function instead of pointer to members:

std::vector<std::function<void()>> vectorOfFunctions;

vectorOfFunctions.push_back(std::bind(&Example::function1, this));
vectorOfFunctions.push_back(std::bind(&Example::function2, this));

This allows you to generalize the vector to hold static member functions or other type of functions.

If you want to stick to member function pointer, it should be

std::vector<void (Example::*)()> vectorOfFunctions;
//                ^^^^^^^^^
vectorOfFunctions.push_back(&Example::function1);
vectorOfFunctions.push_back(&Example::function2);

And invoke them like

(this->*vectorOfFunctions[0])();
(this->*vectorOfFunctions[1])();

BTW: As a supplement to Jans's answer , you can also use std::function with lambda , eg

std::vector<std::function<void ()>> vectorOfFunctions;
vectorOfFunctions.push_back([this]() { this->function1(); });
vectorOfFunctions.push_back([this]() { this->function2(); });

vectorOfFunctions[0]();
vectorOfFunctions[1]();

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