带有 this 的非静态 void 成员指针函数的向量

Vector of non-static void member pointer functions with this

在 C++17 中,如何使用 this 创建非静态成员指针函数的向量并随后调用这些函数?

Example.hpp

class Example{
    public:
        Example();

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

Example.cpp(伪代码)

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;
}

您可以使用 std::function 而不是指向成员的指针:

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

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

这使您可以概括向量以包含静态成员函数或其他类型的函数。

如果要坚持成员函数指针,应该是

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

并像

一样调用它们
(this->*vectorOfFunctions[0])();
(this->*vectorOfFunctions[1])();

顺便说一句:作为 , you can also use std::function with lambda 的补充,例如

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

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