本文介绍了lambda函数可以递归吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一个普通的旧递归函数:
Here is a plain old recursive function:
int fak(int n)
{
return (n <= 1) ? 1 : n * fak(n - 1);
}
我如何将这样的递归函数写为lambda函数?
How would I write such a recursive function as a lambda function?
[](int n) { return (n <= 1) ? 1 : n * operator()(n - 1); }
// error: operator() not defined
[](int n) { return (n <= 1) ? 1 : n * (*this)(n - 1); }
// error: this wasn't captured for this lambda function
推荐答案
是的,他们可以。你可以将它存储在一个变量中并引用该变量(虽然你不能将该变量的类型声明为 auto
,但你必须使用 std :: function
object)。例如:
Yes, they can. You can store it in a variable and reference that variable (although you cannot declare the type of that variable as auto
, you would have to use an std::function
object instead). For instance:
std::function<int (int)> factorial = [&] (int i)
{
return (i == 1) ? 1 : i * factorial(i - 1);
};
否则,不能引用 this
指针从lambda正文内部。
Otherwise, no, you cannot refer the this
pointer from inside the body of the lambda.
这篇关于lambda函数可以递归吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!