2012-04-16 123 views
6

可能重複的模板成員:
Specialization of templated member function in templated class專業模板類

template <class T>  
class MyClass 
{ 
    template <int N> 
    void func() {printf("unspecialized\n");} 
}; 
template<class T> 
template<> 
MyClass<T>::func<0>() 
{ 
    printf("specialzied\n"); 
} 

這是行不通的。是否可以專門化模板類的模板方法?

+1

你應該添加你得到的錯誤信息,因爲「不起作用」真的沒有告訴我們很多。 – sth 2012-04-16 17:23:36

回答

13

它不能按要求完成。出於某種原因(我不知道的理由)明確(即)時封閉類也明確成員模板的專業化只允許(即完全)專業。這個要求在語言標準中明確闡述(參見C++ 98中的14.7.3/18,C++ 11中的C++ 03和14.7.3/16)。

與此同時,構件類的局部模板是允許的,在許多情況下可以被用作一種解決方法(雖然難看)。但是,很明顯,它只適用於模板。當涉及到成員函數模板時,必須使用替代解決方案。

例如,一個可能的解決方法是將調用委託給一個模板類的靜態成員,專門的類,而不是(這常被推薦爲比函數模板http://www.gotw.ca/publications/mill17.htm專業化更好的主意)

template <class T>  
class MyClass 
{ 
    template <int N, typename DUMMY = void> struct Func { 
    static void func() { printf("unspecialized\n"); } 
    }; 

    template <typename DUMMY> struct Func<0, DUMMY> { 
    static void func() { printf("specialized\n"); } 
    }; 

    template <int N> void func() { Func<N>::func(); } 
}; 
+0

謝謝,這就是我發現的 - 我必須專注於包含類。您使用該類功能的解決方案可能是我的最佳解決方案 – 2012-04-16 17:46:04

+0

您是否有此要求的參考?我一直在閱讀標準中看起來相關的部分(從第14.7.3節開始),並且一直未能找到這個要求。 – 2012-04-16 17:50:43

+2

@Jerry:C++ 11§14.7.3/ 16:「* ...除非聲明不明確地專門化類成員模板,如果它的封閉類模板也沒有明確專用的話。」* – ildjarn 2012-04-16 18:00:54