2011-04-17 50 views
2

可能容易解決,但它很難找到一個解決這個模板特殊化:必須有一整套的參數

是否可以(部分)專門用於一整套的類型? 在示例中,「Foo」應僅部分專用於(T,int)和(T,double),只有一個模板定義。

我可以做的是爲(T,int)定義一個專門化。見下文。但是,它應該是(T,int)(T,double)只有一個函數定義(無代碼加倍)。

template <typename T,typename T2> 
struct Foo 
{ 
    static inline void apply(T a, T2 b) 
    { 
    cout << "we are in the generic template definition" << endl; 
    } 
}; 

// partial (T,*) 
template <typename T> 
struct Foo<T, int >  // here something needed like T2=(int, double) 
{ 
    static inline void apply(T a, T2 b) 
    { 
    cout << "we are in the partial specialisation for (T,int)" << endl; 
    } 
}; 

任何想法如何用(T,int)和(T,double)部分專門化一個模板定義?

+1

編譯器怎麼可能知道該怎麼做?它如何知道你想要打印''部分雙精度''等等? – 2011-04-17 16:44:48

+0

輸出僅用於瞭解使用哪個函數定義。 – ritter 2011-04-17 17:04:39

+0

哦,我現在明白了。 – 2011-04-17 17:06:03

回答

0

如果我理解正確的問題,那麼你可以寫一個基類模板,並從中獲得,如下圖所示:

template <typename T, typename U> 
struct Foo_Base 
{ 
    static inline void apply(T a) 
    { 
    cout << "we are in the partial specialisation Foo_Base(T)" << endl; 
    } 
}; 

template <typename T> 
struct Foo<T, int> : Foo_Base<T, int> {}; 

template <typename T> 
struct Foo<T, double> : Foo_Base<T, double> {}; 

雖然它不是一個模板定義(如你要求的),但你可以避免代碼重複。

演示:http://www.ideone.com/s4anA

+0

謝謝你的回答。不幸的是,您使用了原始問題中應用的情況,這並不是這種意圖。需要「兩種」類型作爲功能參數。對不起,我沒有具體說明。 – ritter 2011-04-17 17:43:29

+0

@Frank:讓我編輯答案吧! – Nawaz 2011-04-17 17:46:50

+0

@Frank:現在看我的答案。現在'Foo_Base'需要兩個類型參數,因此我從它派生出來的時候傳遞它們 – Nawaz 2011-04-17 17:48:03

0

我相信你可以做到這一點使用Boost的enable_if啓用你想要的類型局部特殊化。 3.1節展示瞭如何並給出這個例子:

template <class T, class Enable = void> 
class A { ... }; 

template <class T> 
class A<T, typename enable_if<is_integral<T> >::type> { ... }; 
相關問題