Understanding Y Combinator through generic lambdas

前端 未结 1 990
暗喜
暗喜 2020-12-06 03:40

While building a small lambda-based metaprogramming library, I had the necessity of using recursion in a C++14 generic lambda, to implement a left-fold.

My own solut

相关标签:
1条回答
  • 2020-12-06 04:10

    Here is a y combinate where the lambda is passed a recurs that doesn't need to be passed recurs:

    template<class F>
    struct y_combinate_t {
      F f;
      template<class...Args>
      decltype(auto) operator()(Args&&...args)const {
        return f(*this, std::forward<Args>(args)...);
      }
    };
    template<class F>
    y_combinate_t<std::decay_t<F>> y_combinate( F&& f ) {
      return {std::forward<F>(f)};
    };
    

    then you do:

      return y_combinate(step)(acc, xs...);
    

    and change

                       return self(self)(next, y_xs...);
    

    to

                       return self(next, y_xs...);
    

    the trick here is I used a non-lambda function object that has access to its own this, which I pass to f as its first parameter.

    0 讨论(0)
提交回复
热议问题