Search code examples
c++c++20variadic-templatesstdtuple

Transform ith element of std::tuple


Is there any simple way to implement the following pseudo code? Or do you go down a template meta programming rabbit hole?

template <size_t index, typename Func, typename... Args>
auto transform(std::tuple<Args...> tup, Func fn)
{
    return std::tuple{ tup[0], ..., tup[index - 1], fn(tup[index]), ... };
}

Solution

  • Expand the tuple using the template lambda and choose whether to apply the function based on the index of the current element

    #include <tuple>
    
    template<size_t index, size_t I, typename Func, typename Tuple>
    auto transform_helper(Tuple& tup, Func& fn) {
      if constexpr (I < index)
        return std::get<I>(tup);
      else
        return fn(std::get<I>(tup));
    }
        
    template<size_t index, typename Func, typename... Args>
    auto transform(std::tuple<Args...> tup, Func fn) {
      return [&]<std::size_t... I>(std::index_sequence<I...>) {
        return std::tuple{transform_helper<index, I>(tup, fn)... };
      }(std::index_sequence_for<Args...>{});
    }
    

    Demo