2015-11-28 28 views
1

如何獲取類模板以接受可能具有兩個不同參數列表之一的另一個類模板?也就是說,非類型參數或類型和非類型參數:部分專門化具有不同模板參數的模板的模板類

template <int X> 
struct Foo1{}; 

template <typename T, int X> 
struct Foo2{}; 

我希望能夠爲任一這些模板傳遞給我的模板(加上跟隨他們的腳步未來模板)。我希望這說明了我後,雖然語法是全錯:

template <typename T, int X, class> 
struct Magic; //Don't accept non template parameters 

template <typename T, int X, class <int> class C> 
struct Magic<T, X, C> {}; //Template non-type 

template <typename T, int X, class <class, int> class C> 
struct Magic<T, X, C> {}; //Template type and non-type 

我想不出一種方法來寫這些專業化。如果這是不可能的,我可以只有Foo1,並且像它這樣的所有模板都有一個模板類型參數,該模板類型參數不會執行任何操作(template <typename, int X> Foo1{};)並且寫入Magic,但我希望獲得更優雅的解決方案。

+2

[唯一](http://coliru.stacked-crooked.com/a/ac1f9446d910331d)解決方案,我能想到的 –

+0

@PiotrSkotnicki輝煌!如果你想讓它成爲答案,那肯定會回答這個問題。 –

回答

3

您可以應用的一種解決方案是爲每個不同類模板的聲明引入包裝,並根據包裝包裝的內容來專門設計不可思議的結構。最終你需要知道的唯一事情是哪個包裝器與哪個類模板相關聯。

template <int X> 
struct Foo1{}; 

template <typename T, int X> 
struct Foo2{}; 

template <template <int> class C> struct W1; 

template <template <class, int> class C> struct W2; 

template <typename T, int X, class> 
struct Magic; //Don't accept non template parameters 

template <typename T, int X, template <int> class C> 
struct Magic<T, X, W1<C> > {}; //Template non-type 

template <typename T, int X, template <class, int> class C> 
struct Magic<T, X, W2<C> > {}; //Template type and non-type 

int main() 
{ 
    Magic<int, 1, W1<Foo1> > m1; 
    Magic<int, 2, W2<Foo2> > m2; 
} 

DEMO