Quick Q: Can a lambda function be recursive? -- StackOverflow

Quick answer: Yes, use std::function.

This recent short question shows a concise and correct answer, along with a link to a previous more complex example.

Can lambda functions be recursive?

Here is a plain old recursive function:

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

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

  1. [](int n) { return (n <= 1) ? 1 : n * operator()(n - 1); }
  2. // error: operator() not defined
  3.  
  4. [](int n) { return (n <= 1) ? 1 : n * (*this)(n - 1); }
  5. // error: this wasn't captured for this lambda function

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

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.