我最近声明了与此类似的类:
class Foo {
public:
void run();
private:
void foo();
void boo();
void doo();
std::function<void()>getFunction(int);
};
在这个例子中,我想根据传递的整数获取指向成员函数的指针。
void Foo::run(){
std::function<void()> f;
for(int i = 0; i < 3; i++){
f = getFunction(i);
f();
}
}
std::function<void()>Foo::getFunction(int i){
switch(i){
case 0: return foo;
case 1: return Foo::boo;
case 2: return this->*doo;
}
}
所有情况都会导致编译器错误。将 static
添加到 case 1
的函数中是可行的,但我不喜欢使用静态成员。
有没有什么方法可以在不使用 static
关键字的情况下正确获取这些指针?
最佳答案
作为宋元耀回答的延伸
使用 lambda 怎么样? (假设重要的只是能够调用内部函数而不是函数指针本身)
void Foo::run(){
std::function<void()> f;
for(int i = 0; i < 3; i++){
f = getFunction(i);
f();
}
}
std::function<void()> Foo::getFunction(int i) {
switch(i){
case 0: return [this](){this->foo();};
case 1: return [this](){this->boo();};
case 2: return [this](){this->doo();};
}
}
关于c++ - 使用 std::function 包装非静态成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36616388/