问题描述
可能的重复:
c++0x 中的递归 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
是否有任何表达式表示当前的 lambda,以便它可以递归地调用自己?
Is there any expression that denotes the current lambda so it can call itself recursively?
推荐答案
是的,他们可以.您可以将其存储在变量中并引用该变量(尽管您不能将该变量的类型声明为 auto,但您必须使用 std::function 对象代替).例如:
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);
};
否则,不,您不能从 lambda 的主体内部引用 this 指针.
Otherwise, no, you cannot refer the this pointer from inside the body of the lambda.
这篇关于lambda 函数可以递归吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)