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";
}