c++ - Can an anonymous lambda function be bound to an object to allow the code in the lambda to access the object's members?
问题描述
I want to allow a lambda function to access members of an object. There are 2 classes involved here:
The class I want to access
class D {
public:
void doIt() {};
};
An initializer class for management
template<typename T>
class I {
public:
I(std::function<void ()> f) {
someManager->register(this);
_func = f;
}
void run() {
T* t = new T();
auto fn = std::bind(t, _func);
fn();
}
private:
std::function<void ()> _func;
};
static I<D> _init_([]() {
doIt();
});
Then in someManager
I'd call: i->run()
. However, the call to doIt()
is not accepted. What must be changed to make this compile and work?
解决方案
带有修复的工作版本:
class D {
public:
void doIt() {};
};
template<typename T>
class I {
public:
I(std::function<void(D*)> f) {
_func = f;
}
void run() {
T* t = new T();
auto fn = std::bind(_func, t);
fn();
// Alternatively.
_func(t);
}
private:
std::function<void(D*)> _func;
};
I<D> _init_([](D* p) {
p->doIt();
});
int main() {
_init_.run();
}
而不是std::function<void(D*)>
你也可以使用void(*)(D*)
,因为 lambda 表达式[](D* p) { p->doIt();}
不捕获任何东西,因此它可以转换为普通函数指针void(*)(D*)
。
代码也不需要D
在堆上分配,一个自动对象就足够了。例如:
void run() {
T t;
_func(&t);
}
推荐阅读
- python - 按钮在类内时的 Tkinter 按钮命令
- r - 误解曲线函数的问题
- java - 如何从android中的线性布局中获取视图?
- puredata - 如何使用 Pure Data 获取基频并创建其谐波?
- groovy - Error grabbing Grapes -- [download failed: commons-logging#commons-logging;1.2!commons-logging.jar]
- javascript - 如何根据 id 和数量计算数组中的项目总数?
- sql - SQL查询仅显示最近日期的非重复行和重复行
- express - test responsebody with Jest and supertest
- javascript - Html / JS - 在画布上绘制按钮
- asp.net - Azure 应用服务上的 ASP.NET Core 未从应用程序设置中读取连接字符串