4

When I need to implement a recursive lambda, usually I do it like this:

auto factorial = [](auto& self, int n) -> int {
    return n == 0 ? 1 : n * self(self, n - 1);
};

and call it with factorial(factorial, n). However, I've seen people declaring the parameter self with type auto&& instead of auto&. What's the difference?

WeakestTopology
  • 153
  • 2
  • 10

2 Answers2

1

As @appleapple said,

no real difference in your case

That is correct. If you want to know a bit more, perhaps this will interest you: C++ auto& vs auto

1

What's the difference?

The lvalue reference to non-const of your example cannot bind to rvalues.

and call it with factorial(factorial, n)

If you don't ever intend pass an rvalue, then the difference is of no practical consequence.

eerorika
  • 232,697
  • 12
  • 197
  • 326