在 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/