Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ tuple of vectors, create tuple from elements by index

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?

like image 442
Mr. Nobody Avatar asked Jan 31 '18 10:01

Mr. Nobody


1 Answers

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.

like image 63
StoryTeller - Unslander Monica Avatar answered Nov 18 '22 17:11

StoryTeller - Unslander Monica