2012-04-21 94 views
4

我想這樣寫:如何根據類的模板參數特化模板成員函數?

template<typename T1, typename T2> 
class OK 
{ 
    T1 t1; 
    T2 t2; 

public: 
    template<typename TX> const TX & GetRef() const; 
}; 

template<typename T1,typename T2> 
template<> 
const T1 & OK<T1,T2>::GetRef<T1>() const { return t1; } 

template<typename T1,typename T2> 
template<> 
const T2 & OK<T1,T2>::GetRef<T2>() const { return t2; } 

其中VS10無法編譯。

要檢查我的模板專業化的理解,我想和這個編譯沒事兒:

typedef int T1; 
typedef char T2; 
class OK 
{ 
    T1 t1; 
    T2 t2; 

public: 
    template<typename TX> const TX & GetRef() const; 
}; 

template<> 
const T1 & OK::GetRef<T1>() const { return t1; } 

template<> 
const T2 & OK::GetRef<T2>() const { return t2; } 

我缺少什麼?我甚至想做甚麼?

編輯:我想對所有領域的干將,全稱爲GetRef(),因此用戶可以編寫類似:

OK<float,double> ok; 
float a = ok.GetRef<float>(); 
double b = ok.GetRef<double>(); 

回答

5

不能專注一類模板的成員模板不專業模板。也就是說,您要麼提供完整的專業化,其中T1T2固定在班級模板上,然後TX也可以修復,或者您無法修復TX

簡單的解決方案是不專業的模板功能,而是提供不同的過載:

template<typename T1, typename T2> 
class OK 
{ 
    T1 t1; 
    T2 t2; 
public: 
    const T1& GetRef() const { return t1; } 
    template<typename TX> const TX & GetRef() const; 
}; 
+0

我明白了。我想我無法爲t2提供一個getter,也就是GetRef。 – Gabriel 2012-04-21 17:22:48

+2

@Gabriel:沒有......我想我並不真正瞭解你想要做什麼,但爲什麼你不提供兩個不同的函數來返回每個成員?如果你想要的是一個'GetRef',它將返回基於類型的選項,那麼你可以添加一個額外的間接級別來解決它:'template T const&get()const {return get((T *)0 ); }; T1 const&get(T1 *){return t1; } T2 const&get(T2 *){return t2; }'兩個非模板'get'在哪裏是私有的。 – 2012-04-21 17:40:34

+0

不錯!這是訣竅! (你忘了私人獲得順便說一句)謝謝! – Gabriel 2012-04-21 18:00:31

相關問題