lambda-expressions/lambda2.cc - Lambda expressions and recursive calls. | Lecture 3 - slide 2 : 27 Program 4 |
// Recursive lambdas #include <iostream> #include <string> #include <functional> // std::function int main () { using namespace std; auto fac1 = [&](int i){ // Error: auto cannot be used. return i <= 0 ? 1 : i * fac1(i - 1); // Cannot deduce the type of the function. }; function<int(int)>fac2 = [&fac2](int i){ // Use the function<R(A)> type specifier. return i <= 0 ? 1 : i * fac2(i - 1); // Now the type of the lambda does not need to be deduced. }; // The capture is crucial in order to capture fac2. cout << "fac2(5): " << fac2(5) << endl; // fac2(5): 120 }