来自 std::tuple 的向量元组

tuple of vectors from std::tuple

我正在尝试从 std::tuple(原因:https://en.wikipedia.org/wiki/AoS_and_SoA)创建一个向量元组,并得出以下代码。

谁能想到一个更优雅、更简洁的解决方案? PS:我受困于 C++14 编译器...

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_;
};

您可以使用 C++14 std::index_sequence 提取 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.

Class 模板专业化和模式匹配有助于减少代码大小。我在下面添加了一个 static_assert 测试:

#include <tuple>
#include <vector>
#include <type_traits>

template <typename>
struct tuple_of_vectors;

template <typename... Ts>
struct tuple_of_vectors<std::tuple<Ts...>> {
  using type = std::tuple<std::vector<Ts>...>;
};

using t = typename tuple_of_vectors<std::tuple<int,double,float*>>::type;
static_assert(std::is_same<t,std::tuple<std::vector<int>,std::vector<double>,std::vector<float*>>>::value,"");