如何在类中存储lambda并将其捕获为参数
How can I store lambda with capture this in class as parameter?
我在存储lambda表达式时遇到问题,并在类中捕获"this"指针作为参数。我做了这样的typedef:
typedef void(*func)();
下面的代码运行良好。
#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;
}
目前还没有捕获,但当我想在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;
}
我做错了什么?请解释一下。谢谢
不可能从带捕获的lambda转换为函数指针,因为带捕获的lambda包含的信息比函数指针更多(它不仅包含函数的地址,还包含已捕获的变量)。
将typedef void(*func)();
更改为typedef std::function<void()> func;
以获得能够容纳任何可复制函数类型的内容。
正如Angew上面所说,您应该使用std::function
类模板,而不仅仅是函数指针。你的代码会变成这个(从第二个例子复制)
#include <iostream>
#include <functional>
#include <memory>
using namespace std;
class A {
public:
std::function<void> f;
};
class B {
public:
shared_ptr<A> a; // Better ownership
B()
: a(new A())
{
// Now this should work
a->f = [this](){
//Method from class B using "this" pointer
this->p();
};
// Note, you could just do this instead of a lambda:
// a->f = bind(b::p, this);
}
void p() {
printf("Hello!");
}
};
int main() {
B *b = new B();
b->a->f();
return 0;
}
除了正确的可调用对象外,我还通过智能指针添加了A
的自动清理,并添加了代码来向您展示如何使用std::bind
进行清理。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何将lambda作为模板类的成员函数参数
- 使用自动推导的 lambda 参数作为常量表达式
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- 引用捕获和在 lambda 中通过引用发送参数有什么区别 (C++)
- 将__device__ lambda 作为参数传递给 __global__ 函数
- 将 lambda 函数作为参数传递C++
- 如何将 lambda 函数作为参数发送到另一个函数
- Lambda可以用作非类型模板参数吗
- 将参数传递给泛型 lambda 时复制构造函数不正确
- 如何确定捕获不可复制参数的 lambda 的类型?
- 省略C++可变参数 lambda 中的"auto"关键字?
- 如何访问可变参数 lambda 函数参数
- 可变参数 lambda 捕获的解决方法
- 传递给多个参数 lambda 表达式的参数
- 如何编写丢弃其参数的通用可变参数 lambda
- 使用c++参数lambda函数
- 将函数模板"pass"为泛型可变参数 lambda 返回语句是好方法吗?
- c++模板非类型参数lambda函数