Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create tuple of vectors from a Typelist

I have a simple typelist implementation;

template<typename... Ts> 
struct Typelist
{
  static constexpr size_t count{sizeof...(Ts)};
};

What I want to do with it, is for generate an std::tuple of std::vector> for every type in the typelist; for example:

struct A {};
struct B {};
struct C {};

using myStructs = typelist<A,B,C>;
using myList = tupleOfVectorTypes<myStructs>; tuple<vector<A>, vector<B>, vector<C>>

This is what I've been playing around with:

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

However, it keeps spitting back that it expects a type. I've tried wrapping Ts in decltype, like so:

using type = std::tuple<std::vector<decltype(Ts)>...>;

But that's wrong as well, and I'm guessing I'm using decltype incorrectly as well. So, how can I create a tuple of vectors of types, based off the typelist I throw it?

like image 944
Acorn Avatar asked Jun 01 '16 01:06

Acorn


People also ask

Can you have a tuple of vectors in c++?

This article focuses on how to create a 2D vector of tuples in C++. A 2D vector of tuples or vector of vectors of tuples is a vector in which each element is a vector of tuples itself.

What is a vector tuple?

What is Vector of Tuple? A tuple is an object that can hold a number of elements and a vector containing multiple number of such tuple is called a vector of tuple. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed.

What is tuple in R?

Class tuple is used in particular to correctly handle cartesian products of sets. Although tuple objects should behave like “ordinary” vectors, some operations might yield unexpected results since tuple objects are in fact list objects internally. The Summary methods do work if defined for the set elements.


1 Answers

The trick is to use specialization to drill down to the template parameters.

Tested with gcc 5.3.1 in -std=c++1z mode:

#include <vector>
#include <tuple>

template<typename... Ts>
struct Typelist{
};

// Declare List
template<class> class List;

// Specialize it, in order to drill down into the template parameters.
template<template<typename...Args> class t, typename ...Ts>
struct List<t<Ts...>> {
    using type = std::tuple<std::vector<Ts>...>;
};

// Sample Typelist

struct A{};
struct B{};
struct C{};

using myStructs = Typelist<A,B,C>;

// And, the tuple of vectors:

List<myStructs>::type my_tuple;

// Proof

int main()
{
    std::vector<A> &a_ref=std::get<0>(my_tuple);
    std::vector<B> &b_ref=std::get<1>(my_tuple);
    std::vector<C> &c_ref=std::get<2>(my_tuple);
    return 0;
}
like image 94
Sam Varshavchik Avatar answered Oct 05 '22 06:10

Sam Varshavchik