Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

tuple of vectors from std::tuple

I’m trying to create a tuple of vectors from a std::tuple (Reason: https://en.wikipedia.org/wiki/AoS_and_SoA) and came up with the following piece of code.

Can anyone think of a more elegant, less verbose solution? PS: I’m stuck with a C++14 compiler…

template<std::size_t N, class T, template<class> class Allocator>
struct tuple_of_vectors {};

template<class T, template<class> class Allocator>
struct tuple_of_vectors<1, T, Allocator>
{
    using type = std::tuple
    <
        std::vector
        <
            typename std::tuple_element<0, T>::type
                , Allocator<typename std::tuple_element<0, T>::type>
        >
    >;
};

template<class T, template<class> class Allocator>
struct tuple_of_vectors<2, T, Allocator>
{
    using type = std::tuple
    <
        std::vector
        <
            typename std::tuple_element<0, T>::type
                , Allocator<typename std::tuple_element<0, T>::type>
        >,
        std::vector
        <
            typename std::tuple_element<1, T>::type
                , Allocator<typename std::tuple_element<1, T>::type>
        >
    >;
};

// and so on...

template<class T, template<class> class Allocator>
class series
{
public:
    using tov_type = typename tuple_of_vectors
            <std::tuple_size<T>{}, T, Allocator>::type;
        
    tov_type tov_;
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use C++14 std::index_sequence to extract the elements of the tuple.

#include <tuple>
#include <vector>
#include <utility>

template<class IndexSeq, class Tuple, template<class> class Alloc>
struct tuple_of_vectors;

template<class Tuple, template<class> class Alloc, std::size_t... Is>
struct tuple_of_vectors<std::index_sequence<Is...>, Tuple, Alloc> {
  using type = std::tuple<
    std::vector<std::tuple_element_t<Is, Tuple>, 
    Alloc<std::tuple_element_t<Is, Tuple>>>...
  >;
};

template<class Tuple, template<class> class Alloc>
class series {
 public:
  using tov_type = typename tuple_of_vectors<
    std::make_index_sequence<std::tuple_size<Tuple>::value>, Tuple, Alloc>::type;
  tov_type tov_;
};

Demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading