【问题标题】:How to store a virtual member function in std::function?如何将虚拟成员函数存储在 std::function 中?
【发布时间】:2016-03-04 04:00:52
【问题描述】:
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 { }
}

我想将覆盖的“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 { }
}

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

【问题讨论】:

  • 我会摆脱 bind 并使用 lambda - foo() : f{[this] { doSomething(); }} {}。但你所拥有的也有效。

标签: c++ c++11 std-function


【解决方案1】:
this->f = std::bind(&foo::doSomething, this);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 2017-05-03
    • 2011-06-13
    相关资源
    最近更新 更多