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

C++ subtuple from tuple given variadic index sequence

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 ?

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

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

>Solution :

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>{});
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