Created
July 2, 2018 13:12
-
-
Save micjabbour/760d3cbc6b73641b0a436dbdf1a4b560 to your computer and use it in GitHub Desktop.
Recursive lambdas in C++14
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lifted from stackoverflow documentation | |
// the example can currently be found hosted at: | |
// http://www.riptutorial.com/cplusplus/example/8508/recursive-lambdas | |
// original contributors: | |
// - Barry (https://stackoverflow.com/users/2069064/barry) | |
// - Yakk - Adam Nevraumont (https://stackoverflow.com/users/1774667/yakk-adam-nevraumont) | |
// thanks! | |
#include <iostream> | |
#include <utility> | |
template <class F> struct y_combinator { | |
F f; // the lambda will be stored here | |
// a forwarding operator(): | |
template <class... Args> decltype(auto) operator()(Args &&... args) const { | |
// we pass ourselves to f, then the arguments. | |
// the lambda should take the first argument as `auto&& recurse` or similar. | |
return f(*this, std::forward<Args>(args)...); | |
} | |
}; | |
// helper function that deduces the type of the lambda: | |
template <class F> y_combinator<std::decay_t<F>> make_y_combinator(F &&f) { | |
return {std::forward<F>(f)}; | |
} | |
int main() { | |
auto gcd = make_y_combinator([](auto &&gcd, int a, int b) -> int { | |
return b == 0 ? a : gcd(b, a % b); | |
}); | |
std::cout << gcd(21, 9) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment