eSe*_*rus 1 c++ lambda class c++11
我有一个存储lambda表达式的问题,在类中捕获"this"指针作为参数.我做了这样的typedef:
typedef void(*func)();
Run Code Online (Sandbox Code Playgroud)
以下代码工作正常.
#include <iostream>
using namespace std;
typedef void(*func)();
class A {
public:
func f;
};
class B {
public:
A *a;
B() {
a = new A();
a->f = [](){
printf("Hello!");
};
}
};
int main() {
B *b = new B();
b->a->f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
还没有捕获但是当我想在lambda中捕获"this"指针时会抛出错误.如何通过捕获来创建typedef?我想做这样的事情:
#include <iostream>
using namespace std;
typedef void(*func)();
class A {
public:
func f;
};
class B {
public:
A *a;
B() {
a = new A();
//There is a problem with [this]
a->f = [this](){
//Method from class B using "this" pointer
this->p();
};
}
void p() {
printf("Hello!");
}
};
int main() {
B *b = new B();
b->a->f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?请解释一下.谢谢.
无法将带捕获的lambda转换为函数指针,因为带有捕获的lambda包含的信息多于函数指针(它不仅包含函数的地址,还包含已捕获的变量) .
更改typedef void(*func)();为typedef std::function<void()> func;获取能够保存任何可复制函数类型的内容.
| 归档时间: |
|
| 查看次数: |
1953 次 |
| 最近记录: |