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

C++ 将相对函数指针作为参数传递,c++,pointers,stdvector,std-function,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

假设我有一个名称空间
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])();
    }
}
在尝试传递相对函数指针时,出现以下错误:

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
作为指针而不是值传递的具体原因是什么?如果您不绑定任何复制成本很高的参数,我宁愿不这样做

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

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

您能提供“Car::testKey”的代码吗?我在帖子中找不到它。很抱歉,我复制并粘贴了我的生产代码中的错误,并忘记为示例重命名它。它可以通过一个范围为循环进一步简化:
for(auto&f:functions)f()哈,仍然没有习惯所有这些新的C++11东西。我需要传递一个指向std::函数的指针。。。不是函数本身。
std::bind
创建一个包装器,用于存储指向函数的指针和绑定的所有参数。然后将此包装存储在
std::function
中。这里真的没有理由使用指针。我用这个得到了一个错误:
错误C2664:“void KeyManager::press(int,std::function*)”:无法将参数2从“std::_Bind”转换为“std::function*”
这是因为我传递了一个指针,我想传递一个指针,以防在任何时候需要从向量中删除它。
void KeyManager::callFunctions() 
{
    for (auto & f : functions) 
        f();
}