[英]Passing relative function pointers as parameters
Say I have a namespace KeyManager
and I have the function press
说我有一个命名空间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])();
}
}
and I have class Car
and in the constructor of car I want to pass it's relative function pointer to a class function like so: 我有Car
类,在car的构造函数中,我想将其相对函数指针传递给类函数,如下所示:
void Car::printModel()
{
fprintf(stdout, "%s", this->model.c_str());
}
Car::Car(std::string model)
{
this->model = model;
KeyManager::addFunction(this->printModel);
}
I get the following error when trying to pass the relative function pointer: 尝试传递相对函数指针时出现以下错误:
error C3867: 'Car::printModel': function call missing argument list; use '&Car::printModel' to create a pointer to member
How do I fix this? 我该如何解决?
You have to use std::bind
to create an std::function
that invokes a member function on a specific object. 您必须使用std::bind
创建一个std::function
来调用特定对象上的成员函数。 This is how that works: 这是这样的:
Car::Car(std::string model)
{
this->model = model;
KeyManager::addFunction(std::bind(&Car::printModel, this));
}
Is there a specific reason why you are passing the std::function
as pointer, instead of a value? 为什么将std::function
作为指针而不是值传递给特定原因? If you are not binding any arguments that are expensive to copy, I would rather not do that. 如果您不绑定任何复制成本很高的参数,我宁愿不这样做。
Also, callFunctions
can be simplified using a lambda: 另外,可以使用lambda简化callFunctions
:
void KeyManager::callFunctions()
{
for (auto & f : functions)
f();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.