I've got a template class, that has tuple, filled by vectors.
template<typename ...Ts>
class MyClass
{
public:
std::tuple<std::vector<Ts>...> vectors;
};
I want to get new tuple filled by vectors element on 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 this even possible?
You can accomplish it rather easily in C++14 it with the usual technique of a helper function that accepts an index sequence 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 just calls std::get<I>
for the ordinal of each type, and then calls at
on the vector at that place. I used at
in case the vectors aren't all holding an item at that index, but you can substitute for operator[]
if your case doesn't require the check. All the results are then sent to make_tuple
to construct the result tuple object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With