简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM