問題描述
可能的重復:
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模板網!