lambda 函数可以递归吗? [英] Can lambda functions be recursive?

查看:47
本文介绍了lambda 函数可以递归吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
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 函数可以递归吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆