如何向被std::function<void()>包装的类成员函数传递参数
问题解决:C++父类任务队列传递带参数子类成员函数的实现方法
错误原因
你编写的第9帧绑定代码同时混用了std::bind和lambda语法,存在两个核心错误:
- 调用非静态成员函数
f_Child2时没有绑定对应的this指针,非静态成员函数必须依赖类实例才能调用 - 语法结构混乱,lambda的捕获列表、bind的参数顺序完全不符合C++语法规范
解决方案
有两种常用的实现方式,推荐优先使用lambda写法,可读性更高:
方案1:lambda实现(推荐)
和你之前传递带参自由函数的语法完全一致,只需要额外捕获this指针即可调用子类成员函数:
// 替换原来错误的第9帧addTask代码 addTask(9, [this, a = 4]() { f_Child2(a); });
方案2:std::bind实现
如果要使用bind,需要严格按照bind的参数顺序传值:第一个参数是成员函数指针,第二个是类实例指针(this),之后依次传入成员函数需要的参数:
// 替换原来错误的第9帧addTask代码 addTask(9, std::function<void()>{ std::bind(&Child::f_Child2, this, 4) });
完整可运行代码
#include <iostream> #include <vector> #include <map> #include <functional> void f_Free1() { std::cout << "Hi there hello. I'm a free function without arguments."; } void f_Free2(int i) { std::cout << "Hi there hello. I'm a free function with an argument. It's " << i; } class Parent { std::map<unsigned int, std::vector<std::function<void()>>> Tasks; protected: void addTask(unsigned int frame, std::function<void()> task) { Tasks[frame].push_back(task); } public: virtual ~Parent() {} unsigned int Frame = 0; void tick() { if (Tasks.count(Frame)) { for (auto task : Tasks[Frame]) { task(); } } Frame++; } }; class Child : public Parent { void f_Child1() { std::cout << "This is a private Child function without arguments. "; } void f_Child2(int i) { std::cout << "This is a private Child function with an argument. It's " << i; } public: Child() { addTask(3, f_Free1); addTask(5, [a = int(4)] () { f_Free2(a); } ); addTask(7, std::function<void()> { std::bind(&Child::f_Child1, this) }); // 修正后的代码,这里用lambda方案,也可替换为bind方案 addTask(9, [this, a = 4]() { f_Child2(a); }); } }; int main() { Child child; for (unsigned int i = 0; i < 12; i++) { std::cout << "[" << child.Frame << "]"; child.tick(); std::cout << std::endl; } return 0; }
运行输出效果
[0] [1] [2] [3]Hi there hello. I'm a free function without arguments. [4] [5]Hi there hello. I'm a free function with an argument. It's 4 [6] [7]This is a private Child function without arguments. [8] [9]This is a private Child function with an argument. It's 4 [10] [11]
内容的提问来源于stack exchange,提问作者Nathaniel G.M.
相关产品推荐
相关产品推荐

