C ++ tuple of vectors, creating a tuple of elements by index

I have a template class that has a tuple filled with vectors.

template<typename ...Ts> class MyClass { public: std::tuple<std::vector<Ts>...> vectors; }; 

I want to get a new tuple filled with a vector element at the specified index.

 template<typename ...Ts> class MyClass { public: std::tuple<std::vector<Ts>...> vectors; std::tuple<Ts...> elements(int index) { // How can I do this? } }; 

Is it possible?

+5
source share
1 answer

You can easily do this in C ++ 14 using the usual helper function technique, which takes a sequence of indices as an added parameter:

 template<std::size_t... I> auto elements_impl(int index, std::index_sequence<I...>) { return std::make_tuple( std::get<I>(vectors).at(index)... ); } auto elements(int index) { return elements_impl(index, std::index_sequence_for<Ts...>{}); } 

It simply calls std::get<I> for the sequence number of each type, and then calls at on a vector at that location. I used at if vectors do not all hold an element at this index, but you can replace operator[] if your case does not require verification. Then all the results are sent to make_tuple to build the result set object.

+8
source

Source: https://habr.com/ru/post/1275071/


All Articles