繁体   English   中英

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

[英]Use std::function to wrap non-static member function pointer

我最近宣布了类似的类:

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

所有情况都会导致编译器错 case 1添加static功能,但我不想使用静态成员。

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

作为宋元瑶的答案的延伸

怎么用lambdas? (假设它只是能够调用内部函数而不是函数指针本身很重要)

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

LIVE3

你需要绑定一个对象来调用非静态成员函数,在这种情况下就是this 你可以使用std::bind

std::function<void()> Foo::getFunction(int i) {
    switch(i){
        case 0: return std::bind(&Foo::foo, *this); // or std::bind(&Foo::foo, this)
        case 1: return std::bind(&Foo::boo, *this); // or std::bind(&Foo::boo, this)
        case 2: return std::bind(&Foo::doo, *this); // or std::bind(&Foo::doo, this)
    }
}

LIVE1

或者将std::function<void()>更改为std::function<void(Foo&)> ,以匹配非静态成员函数。 然后

void Foo::run() {
    std::function<void(Foo&)> f;
    for(int i = 0; i < 3; i++) {
        f = getFunction(i);
        f(*this);
    }
}

std::function<void(Foo&)> Foo::getFunction(int i) {
    switch(i){
        case 0: return &Foo::foo;
        case 1: return &Foo::boo;
        case 2: return &Foo::doo;
    }
}

LIVE2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM