我找到了一篇关于如何创建递归 lambda的帖子,但不清楚如何从函数中返回它。
据我所知,在下面的代码中,捕获func是指被销毁的对象:
#include <iostream>
#include <functional>
std::function<int (int)> make_lambda()
{
std::function<int (int)> func;
func = [&func](int val)
{
if (val < 10)
{
return func(val + 1);
}
return val;
};
return func;
}
int main()
{
std::cout << make_lambda()(0);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何使这段代码工作?
有没有比使用更好的方法std::shared_pointer<std::function<int (int)>>?
void make_lambda(std::function<int (int)>&) 不是一个选择。
编辑1:
为什么this不允许 lambdas 引用自己?
Y 组合子是你的朋友。
template<class R, class...Args>
auto Y = [] (auto f) {
auto action = [=] (auto action) -> std::function<R(Args...)> {
return [=] (Args&&... args)->R {
return f( action(action), std::forward<Args>(args)... );
};
};
return action(action);
};
Run Code Online (Sandbox Code Playgroud)
现在只是:
return Y<int, int>([](auto&& self, int val)
{
if (val < 10)
{
return self(val + 1);
}
return val;
});
Run Code Online (Sandbox Code Playgroud)
和噗,魔法。
您不能this在 lambda 中使用来指代 lambda 本身,因为它指的是封闭对象this。
显式this参数提议可以让你避免这个问题。但这不在c++20 中。
最后我检查,语法看起来有点像:
return [](this auto&& self, int val) {
if (val < 10)
return self(val+1);
return val;
};
Run Code Online (Sandbox Code Playgroud)
您的*this参数作为第一个参数传递的位置,包括其 r/lvalue 类别。
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |