c++ - 带有 this 的非静态 void 成员指针函数的 vector

标签 c++ vector pointer-to-member

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

例子.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));

这允许您泛化 vector 以包含静态成员函数或其他类型的函数。

关于c++ - 带有 this 的非静态 void 成员指针函数的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53164610/

相关文章:

c++ - Qt 脚本多线程

c++ - 获取子进程C++的执行结果

c++ - 如何使用 boost::bind 将成员函数绑定(bind)到任何对象

c++ - 专门针对 const 成员函数指针

c++ - C/C++ 如何在连续两次输入 Enter 后或在 2 个换行符后从 stdin 读取

c++ - C++ 函数声明中,右括号前的 & 符号有何作用?

C++ vector - 访问在结构中声明的结构类型 vector 的大小

c++ - 无法从 C++ vector 中删除元素

c++ - std::vector 指针?

c++ - 基于用户表达式在编译时参数化函数