成员函数向量

时间:2018-02-20 12:47:04

标签: c++

使用向量来调度类的方法调用的方法是什么。我想有一个方法向量,如下所示:

class Model {
    using task_t = std::function<void()>;
    std::vector<std::vector<task_t>> _frameTasks;

    void add_function() { _frameTasks[3].push_back(&(this->function()); }
    void function() {std::cout << "hi"; }
    void step() {
         for (auto task : _frameTasks[3]) task();
    }
}

但是编译器抱怨说:

error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function. 

我如何解决这个问题或者什么是正确的方法?

1 个答案:

答案 0 :(得分:2)

&(this->function())正在将&应用于function()成员函数调用的结果。默认operator&需要左值,但表达式this->function()不是左值。

&Model::function不会起作用,因为它是指向成员函数的指针(而不是指向函数的指针)。它的类型为void (Model::*)(),即:指向Model(非static成员函数的指针,它不带任何参数并且不返回任何内容。

您需要某种方式来指定将调用Model 成员函数function() 对象

从C ++ 11开始,只需使用 lambda expression 即可实现这一目标:

void add_function() {
    _frameTasks[3].push_back(
        [this](){ add_function(); }
    );
}
相关问题