lambda 函数可以递归吗?

2021-12-16 00:00:00 递归 lambda c++ c++11

可能的重复:
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.

相关文章