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

标签 c++ pointers stdvector std-function

假设我有一个命名空间 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 类,在 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 作为指针而不是值传递是否有特定原因?如果您不绑定(bind)任何复制成本高昂的参数,我宁愿不这样做。

此外,callFunctions 可以使用 lambda 进行简化:

void KeyManager::callFunctions() 
{
    for (auto & f : functions) 
        f();
}

关于c++ - 将相对函数指针作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20145483/

相关文章:

c++ - Linux 进程文件包含哪些内容?

c++ - 针对库的静态链接实际上做了什么?

c++ - 添加指针的好处,何时使用指针以及为什么

c++ - 从带有原始指针的 vector 中删除 std::unique_ptr 的最佳方法?

c++ - 如何使用迭代器在 vector 中的不同位置插入多个元素?

c++ - 用 const 重载运算符 <,但不要作为 const 插入 map

c++ - 如果我们不想要模板/泛型中的任何数据类型怎么办

c++ - 学习重载运算符。获取 "non-standard syntax; use ' &' to create a pointer to a member"错误

C++ 指向一个对象然后移动它的内存位置

c++ - Windows 中的 IPC 共享内存 std::vector