【问题标题】:Passing relative function pointers as parameters将相对函数指针作为参数传递
【发布时间】:2013-11-22 12:56:17
【问题描述】:

假设我有一个命名空间 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 类,在汽车的构造函数中,我想将它的 relative 函数指针传递给一个类函数,如下所示:

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

我该如何解决这个问题?

【问题讨论】:

  • 能否请您提供“Car::testKey”的代码,我在帖子中没有找到。
  • 对不起,我从生产代码中复制并粘贴了错误,忘记重命名示例。

标签: c++ pointers stdvector std-function


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 它可以通过范围 for 循环进一步简化:for (auto &amp; f : functions) f();
  • 哈,还没有习惯所有这些新的 C++11 东西。
  • 我需要传递一个指向 std::function 的指针...而不是函数本身。
  • std::bind 创建一个包装器,用于存储指向函数的指针和您绑定的所有参数。然后将该包装器存储在std::function 中。真的没有理由在这里使用指针。
  • 我在使用这个时遇到了一个错误:error C2664: 'void KeyManager::press(int,std::function&lt;void (void)&gt; *)' : cannot convert argument 2 from 'std::_Bind&lt;true,void,std::_Pmf_wrap&lt;void (__thiscall Car::* )(void),void,Car,&gt;,Car *const &gt;' to 'std::function&lt;void (void)&gt; *' 这是因为我传递了一个指针,我想传递一个指针,以防万一我需要从向量中删除它。跨度>
猜你喜欢
  • 2020-11-08
  • 2021-12-18
  • 2017-03-17
  • 1970-01-01
  • 2013-03-16
  • 2015-01-29
  • 2019-08-17
  • 2012-11-28
  • 2012-01-24
相关资源
最近更新 更多