C++ lambda 函数可以递归吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14531993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:25:05  来源:igfitidea点击:

Can lambda functions be recursive?

c++recursionc++11lambda

提问by fredoverflow

Possible Duplicate:
Recursive lambda functions in c++0x

可能的重复:
c++0x 中的递归 lambda 函数

Here is a plain old recursive function:

这是一个普通的旧递归函数:

int fak(int n)
{
    return (n <= 1) ? 1 : n * fak(n - 1);
}

How would I write such a recursive function as a lambda function?

我将如何编写这样的递归函数作为 lambda 函数?

[](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

Is there any expression that denotes the current lambda so it can call itself recursively?

是否有任何表示当前 lambda 的表达式,以便它可以递归地调用自己?

回答by Andy Prowl

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::functionobject instead). For instance:

是的他们可以。您可以将它存储在一个变量中并引用该变量(尽管您不能将该变量的类型声明为auto,但您必须改用一个std::function对象)。例如:

std::function<int (int)> factorial = [&] (int i) 
{ 
    return (i == 1) ? 1 : i * factorial(i - 1); 
};

Otherwise, no, you cannot refer the thispointer from inside the body of the lambda.

否则,不,您不能this从 lambda 的主体内部引用指针。