Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you generate a variadic template pack from a size and its content?

Consider the following code :

template<unsigned int... TSIZE>
struct Base {};
template<unsigned int TORDER, unsigned int TDIM>
struct Derived : public Base</* TDIM, TDIM, ... TDIM (TORDER times) */> {};

Do you think that a trick exists to correctly generate the template parameters of Base on the second line of this example ? For example I want Derived<3, 5> to inherit from Base<5, 5, 5>. How to do that ?

like image 602
Vincent Avatar asked Aug 15 '12 08:08

Vincent


1 Answers

With a bit of TMP, this isn't that hard after all:

template<unsigned ToGo, class T, T Arg, template<T...> class Target, T... Args>
struct generate_pack
  : generate_pack<ToGo-1, T, Arg, Target, Args..., Arg>
{ // build up the 'Args' pack by appending 'Arg' ...
};

template<class T, T Arg, template<T...> class Target, T... Args>
struct generate_pack<0, T, Arg, Target, Args...>
{ // until there are no more appends to do
  using type = Target<Args...>;
};

template<unsigned Num, class T, T Arg, template<T...> class Target>
using GeneratePack = typename generate_pack<Num, T, Arg, Target>::type;

template<unsigned int... TSIZE>
struct Base{};

template<unsigned int TORDER, unsigned int TDIM> 
struct Derived
  : GeneratePack<TORDER, unsigned, TDIM, Base>
{
};

Live example.

like image 123
Xeo Avatar answered Sep 20 '22 15:09

Xeo