9

考虑以下代码:

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

您认为在本例的第二行中正确生成 Base 的模板参数是否存在技巧?例如我想Derived<3, 5>继承自Base<5, 5, 5>. 怎么做 ?

4

1 回答 1

10

有了一点 TMP,这毕竟不是那么难:

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

活生生的例子。

于 2012-08-15T08:41:43.857 回答