最近,我阅读了Barry对这个问题Recursive lambda functions in C++11的回答:
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.
// [edit: Barry] pass in std::ref(*this) instead of *this
return f(std::ref(*this), std::forward<Args>(args)...);
}
};
// deduction guide
template <class F> y_combinator(F) -> y_combinator<F>;
Run Code Online (Sandbox Code Playgroud)
基本上,y_combinator允许更轻松地编写递归 lambda 表达式(例如,无需 delcare a std::function)。当我玩的时候y_combinator,我发现了一些奇怪的东西: …