Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading