A tuple of an arbitrary but time-compiled number of types

Let's say I have a type that is parameterized by another integral POD type:

template< size_t N > struct MyFoo { /* ... */ }; 

With it you can get a tuple of them:

 typedef std::tuple< MyFoo< 1 >, MyFoo< 2 >, MyFoo< 3 > > Foo3; 

But now I want to have type " Foo< N > ", where N is constexpr . One way to achieve something similar to Foo< N > would be to:

 template< size_t N > struct Foos; template<> struct Foos< 1 >{ typedef std::tuple< MyFoo< 1 > > type; }; template<> struct Foos< 2 >{ typedef std::tuple< MyFoo< 1 >, MyFoo< 2 > > type; }; /* continue with this.... */ 

th. specialize it manually for every N I want. Is there a more general way to do this?

Thanks:)

+4
source share
2 answers
 template<std::size_t N, std::size_t... Is> struct MakeFoos : MakeFoos<N - 1, N, Is...> { }; template<std::size_t... Is> struct MakeFoos<0, Is...> { using type = std::tuple<MyFoo<Is>...>; }; template<std::size_t N> struct Foos { using type = typename MakeFoos<N>::type; }; 

To get your tuple, write Foos<3>::type .

+2
source

You will need a mechanism to create a sequence of integers from 1 to N. The rest is pretty simple:

 #include <cstddef> #include <tuple> // to generate a sequence of indices: template<size_t... Ns> struct indices { typedef indices< Ns..., sizeof...( Ns ) > next; }; template<size_t N> struct make_indices { typedef typename make_indices< N - 1 >::type::next type; }; template<> struct make_indices< 0 > { typedef indices<> type; }; // create a sequence and expand it inside a typedef template<size_t N> struct MyFoo {}; template< size_t N > struct Foos { template<typename> struct Helper; template<size_t... Ns> struct Helper<indices<Ns...>> { typedef std::tuple< MyFoo<Ns>... > type; }; typedef typename Helper< typename make_indices<N>::type >::type type; }; 

Live demo.

+3
source

All Articles