将相对函数指针作为参数传递
Passing relative function pointers as parameters
>假设我有一个命名空间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();
}
相关文章:
- 使用指向成员的指针将成员函数作为参数传递
- 修改函数中的指针(将另一个指针作为参数传递)
- 将成员函数指针作为参数传递给模板方法
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将函数指针数组中的函数指针作为模板参数传递
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 如何将指针变量作为引用参数传递?
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- Qt5 - 如何将"QList<T> *"指针作为信号参数传递,并在完成后将其删除?
- C++将指向成员的指针作为模板参数传递
- 通过引用函数传递指针参数是什么意思?
- C++ 将派生类的成员函数指针作为参数传递时选择了错误的模板专用化
- 将函数指针作为函数参数传递的目的
- 将派生类作为参数传递给方法,该方法是具有智能指针的基类
- 使用 C++11 将指向成员函数的指针作为参数传递
- 如何在程序集函数中将元素数组作为参数传递时转发 ARM 寄存器的地址指针
- 在一行中将默认类型值上的指针作为参数传递
- 将双指针作为参数传递给需要引用 std::vector <double>的函数