Search code examples
c++templatesc++17variadic-templatesfold-expression

Can you achieve fn(x1 ^ fn(x0)) with a fold expression?


Is it possible to achieve the following using a fold expression?

template<class... Args>
auto foo(Args... args)
{
    //calling foo(x0, x1, x2) should be exactly equivalent to
    //calling fn(x2 ^ fn(x1 ^ fn(x0)))
}

Solution

  • If you insist on a fold expression, something along these lines could probably be made to work (not tested):

    template <typename T>
    struct Wrapper {
      T& val;
    };
    
    template <typename T, typename U>
    auto operator^(Wrapper<T> l, Wrapper<U> r) {
      return Wrapper(r.val ^ fn(l.val));
    }
    
    template<class... Args>
    auto foo(Args... args)
    {
      return fn((... ^ Wrapper<Args>(args)).val);
    }