How can I get the first N elements of a tuple c++?

279 Views Asked by At

lets say I had a function like the following, how could I get the first n elements of a tuple?

template<std::size_t N, class... Ts>
void foo(Ts... ts){
   std::tuple<Ts...> all_elements(ts...);
   auto first_elements = //the first N elements of the tuple all_elements
}

What would be the best way to define the variable first_elements with the first N elements of the all_elements tuple?

Update

This is just going off of Sam Varshavchik's answer for a version compatible with lower versions of C++ such as C++17 as well:

template<typename T, T... ints, class...DTs>
auto reduce_tuple(std::integer_sequence<T, ints...> int_seq, std::tuple<DTs&&...>&& t){
    return std::forward_as_tuple((std::move(std::get<ints>(t)))...);
}

template<std::size_t N, class... Ts>
auto foo(Ts... ts){
   std::tuple<Ts&&...> all_elements(std::forward<Ts>(ts)...);
   return reduce_tuple(std::make_index_sequence<N>{}, std::move(all_elements));  
}

//usage
int main(){
    auto t=foo<2>(3, "a", 0.1);

    static_assert(std::is_same_v<decltype(t), std::tuple<int, const char*>>);

    std::cout << std::get<0>(t) << " " << std::get<1>(t) << "\n";
}

1

There are 1 best solutions below

0
Sam Varshavchik On BEST ANSWER

Here's a classical C++20 solution: use a template closure, in combination with std::integer_sequence.

Let's improve things a little bit by using universal references and a forwarding tuple in order to minimize the number of copies.

Rather than defining a tuple the following example forwards the first N parameters to another function.

And by sheer coincidence, the function in question is std::make_tuple that ...produces a tuple. But, any function will do.

#include <tuple>
#include <utility>
#include <iostream>
#include <type_traits>

template<std::size_t N, typename ...Ts>
auto foo(Ts && ...ts)
{
    auto all_elements=std::forward_as_tuple(
        std::forward<Ts>(ts)...
    );

    return [&]<std::size_t ...I>(std::index_sequence<I...>)
        {
            return std::make_tuple(std::get<I>(all_elements)...);
        }(
            std::make_index_sequence<N>{}
        );
}

int main()
{
    auto t=foo<2>(3, "a", 0.1);

    static_assert(std::is_same_v<decltype(t), std::tuple<int, const char*>>);

    std::cout << std::get<0>(t) << " " << std::get<1>(t) << "\n";
}

(live demo)