Reputation: 23
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_;
};
Upvotes: 1
Views: 1064
Reputation: 11037
Class template specialisation and pattern matching can help reduce the code size. I include a static_assert
test below:
#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,"");
Upvotes: 0
Reputation: 42756
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_;
};
Upvotes: 2