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