将相对函数指针作为参数传递

Passing relative function pointers as parameters

本文关键字:参数传递 指针 相对 函数      更新时间:2023-10-16

>假设我有一个命名空间KeyManager并且我有函数press

std::vector<std::function<void()>*> functions;
void KeyManager::addFunction(std::function<void()> *listener)
{
    functions.push_back(listener);
}
void KeyManager::callFunctions()
{
    for (int i = 0; i < functions.size(); ++i)
    {
        // Calling all functions in the vector:
        (*functions[i])();
    }
}

我有类Car,在汽车的构造函数中,我想将其相对函数指针传递给类函数,如下所示:

void Car::printModel()
{
    fprintf(stdout, "%s", this->model.c_str());
}
Car::Car(std::string model)
{
    this->model = model;
    KeyManager::addFunction(this->printModel);
}

尝试传递相对函数指针时出现以下错误:

error C3867: 'Car::printModel': function call missing argument list; use '&Car::printModel' to create a pointer to member

我该如何解决这个问题?

您必须使用 std::bind 来创建调用特定对象上的成员函数的std::function。这是它的工作原理:

Car::Car(std::string model)
{
    this->model = model;
    KeyManager::addFunction(std::bind(&Car::printModel, this));
}

std::function作为指针而不是值传递是否有特定原因?如果你不绑定任何复制成本高昂的论点,我宁愿不这样做。

此外,可以使用 lambda 简化callFunctions

void KeyManager::callFunctions() 
{
    for (auto & f : functions) 
        f();
}
相关文章: