[英]How to specialize a template member function depending on the class' template arguments?
我想寫這個:
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; }
我錯過了什么? 我甚至想做什么?
編輯 :我想擁有所有字段的getter,都叫做GetRef()
,所以用戶可以這樣寫:
OK<float,double> ok;
float a = ok.GetRef<float>();
double b = ok.GetRef<double>();
如果不專門化模板,則無法專門化類模板的成員模板。 也就是說,要么提供完整的專業化, T1
和T2
固定在類模板上,然后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;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.