85

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

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?

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

6
  • 1
    possible with huge std::function overhead or with polymorphic lambdas.
    – ipc
    Jan 25, 2013 at 23:36
  • @MichaelBurr, Great link you have there.
    – chris
    Jan 25, 2013 at 23:40
  • 2
    Oops - I accidentally deleted my comment. here's the link back: blogs.msdn.com/b/vcblog/archive/2008/11/18/… Jan 25, 2013 at 23:44
  • @MichaelBurr, It's funny. I find the notion that you accidentally deleted your comment laughable, but I can relate to how easy it is to do something like that :p
    – chris
    Jan 25, 2013 at 23:46
  • I'm just gonna leave this here slideshare.net/adankevich/c11-15621074 29 slide
    – innochenti
    Jan 29, 2013 at 19:06

1 Answer 1

120

Yes, they can. Starting with C++23 you can use the explicit this parameter:

auto factorial = [](this auto self, int i) 
{ 
    return (i == 1) ? 1 : i * self(i - 1); 
};

With previous C++ standards, you can store the lambda 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); 
};
12
  • 2
    I think factorial needs to be captured by reference, but I'm not 100% positive.
    – ildjarn
    Jan 25, 2013 at 23:43
  • 30
    Also note that such a function cannot be returned safely. Jan 25, 2013 at 23:50
  • 4
    @R.MartinhoFernandes: Good point, it would capture by reference a local object that is gone out of scope. You could still use a shared_ptr I guess (?), but that would be probably kind of fetish.
    – Andy Prowl
    Jan 25, 2013 at 23:56
  • 1
    @rikimaru2013 returning it destroys the local variable, and the function has a reference to that local variable. May 12, 2016 at 14:45
  • 3
    Hmm, why can't auto be used for the lambda's type? I'd expect this to be possible as long as I specify return type for the lambda body. Silly C++ :( Aug 12, 2016 at 14:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.