如何在std :: function中存储虚拟成员函数?

sop*_*hia 2 c++ c++11 std-function

class foo
{
public:
    foo(void)
    {
        this->f = std::bind(&foo::doSomething, this);
    }

private:
    virtual void doSomething(void) { }

private:
    std::function<void(void)> f;
}

class bar : public foo
{
public:
    bar(void) { /* I have no idea what I have to */ }

private:
    virtual void doSomething(void) override { }
}
Run Code Online (Sandbox Code Playgroud)

我想将覆盖的'doSomething'函数分配给'foo :: f'.但我不知道如何分配重写'doSomething'功能.或者我只是编写一些代码来为每个类分配'doSomething'函数?

class foo
{
public:
    foo(void)
    {
        this->f = std::bind(&foo::doSomething, this);
    }

private:
    virtual void doSomething(void) { }

private:
    std::function<void(void)> f;
}

class bar : public foo
{
public:
    bar(void) 
    {  
        this->f = std::bind(&bar::doSomething, this);
    }

private:
    virtual void doSomething(void) override { }
}
Run Code Online (Sandbox Code Playgroud)

那段代码是我对我的问题的回答.但我想我可以自动将虚函数分配给std :: function.

Wea*_*ish 6

this->f = std::bind(&foo::doSomething, this);
Run Code Online (Sandbox Code Playgroud)

这很好用.通过指针或引用传递对象将允许它调用正确的虚函数.