#include <iostream>
/*
================================
ANONYMOUS RECURSION
USING A Y‑COMBINATOR WRAPPER
================================
Problem:
Lambdas in C++ cannot call themselves directly because
they have no name.
Solution:
Create a wrapper class (Y) that stores a lambda and
passes itself as the first argument, enabling recursion.
How it works:
- The lambda receives "self" as its first parameter.
- It calls self(...) to recurse.
- No std::function, no heap allocation, no type erasure.
- Fully inline and efficient.
*/
// Y‑combinator wrapper class
template <class F>
class Y {
F f; // store the lambda
public:
explicit Y(F&& f) : f(std::forward<F>(f)) {}
// operator() forwards arguments to the lambda,
// passing *this as the "self" parameter.
template <class... Args>
decltype(auto) operator()(Args&&... args) const {
return f(*this, std::forward<Args>(args)...);
}
};
// Helper function to construct Y objects
template <class F>
auto make_recursive(F&& f) {
return Y<F>(std::forward<F>(f));
}
int main() {
/*
Example: factorial using anonymous recursion.
The lambda signature:
[](auto self, int n) -> long long
- "self" is the recursive function.
- "n" is the argument.
*/
auto factorial = make_recursive(
[](auto self, int n) -> long long {
if (n <= 1) return 1;
return n * self(n - 1); // recursive call
}
);
int x = 6;
long long result = factorial(x);
std::cout << "factorial(" << x << ") = " << result << "\n";
}
/*
run:
factorial(6) = 720
*/