y_combinator in C++

y_combinator in C++

来源:https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0200r0.html

1. 模板

cpp <y_combinator>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <functional>
#include <utility>

template <class Fun>
class y_combinator_result {
Fun fun_;

public:
template <class T>
explicit y_combinator_result(T &&fun) : fun_(std::forward<T>(fun)) {}
template <class... Args>
decltype(auto) operator()(Args &&...args) {
return fun_(std::ref(*this), std::forward<Args>(args)...);
}
};
template <class Fun>
decltype(auto) y_combinator(Fun &&fun) {
return y_combinator_result<std::decay_t<Fun>>(std::forward<Fun>(fun));
}

2. 用法

cpp
1
2
3
4
5
6
int main() {
std::vector<std::vector<int>> G;
y_combinator([&](auto dfs, int u) -> void {
for (auto v : G[u]) dfs(v);
})(1);
}

y_combinator in C++
https://blog.fredbill.eu.org/2024/01/11/编程/y-combinator-in-C/
作者
FredBill
发布于
2024年1月11日
许可协议