Home > Mobile >  C subtuple from tuple given variadic index sequence
C subtuple from tuple given variadic index sequence

Time:05-02

Assume I have a std::tuple, I'd like to write a function which receives a tuple and a variadic sequence outputting a subtuple containing the columns corresponding to those indexes.

Example usecase:

std::tuple<int, char, float, std::string> t{1, 'd', 3.14, "aaa"};

auto subtuple = extract_subtuple(t, 0, 2);
// returns std::tuple<int, float>(1, 3.14)

Is this possible ?

I had a look at this other question but in the end I didn't find what I was looking for.

CodePudding user response:

You can't do it directly because tuple indices should be constant expressions and function parameters are never constant expressions even if corresponding arguments are. You have two main options.

Firstly, you could make indices template parameters:

template<std::size_t... Is, class... Ts>
auto extract_subtuple(const std::tuple<Ts...>& tuple) {
    return std::make_tuple(std::get<Is>(tuple)...);
}

auto subtuple = extract_subtuple<0, 1>(t);

Secondly, if you want to make indices function parameters, you could wrap them into types:

template<class... Ts, class... Indices>
auto extract_subtuple(const std::tuple<Ts...>& tuple, Indices...) {
    return std::make_tuple(std::get<Indices::value>(tuple)...);
}

template<std::size_t I>
using Idx = std::integral_constant<std::size_t, I>;

auto subtuple = extract_subtuple(t, Idx<0>{}, Idx<1>{});
  • Related