2012-08-15 71 views
9

考慮下面的代碼:您可以根據大小及其內容生成可變模板包嗎?

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

你認爲一招的存在是爲了正確地產生在這個例子中的第二線基地的模板參數?例如,我想要Derived<3, 5>繼承自Base<5, 5, 5>。怎麼做 ?

回答

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

Live example.

+0

哦,你可以遞歸派生?這很酷。 – jrok 2012-08-15 08:43:21

+1

它被Boost.MPL作者稱爲模板元函數轉發。 – TemplateRex 2012-08-15 08:53:59

相關問題