使用 std::function 包装非静态成员函数指针

Gie*_*but 3 c++ function-pointers c++11

我最近声明了与此类似的类:

class Foo {
public:
    void run();
private:
    void foo();
    void boo();
    void doo();
    std::function<void()>getFunction(int);
};
Run Code Online (Sandbox Code Playgroud)

在此示例中,我想根据传递的整数获取指向成员函数的指针。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

所有情况都会导致编译器错误。添加static到功能是case 1有效的,但我不喜欢使用静态成员。

有没有办法在不使用static关键字的情况下正确获取这些指针?

ale*_*efr 5

作为宋元耀答案的延伸

使用 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();}; 
    }
}
Run Code Online (Sandbox Code Playgroud)

直播3