2013-01-15 39 views
1

我一直在努力確保理解C++模板的語法,並且我認爲我只能說明最後一種情況。如果我有一個模板類,它有一個模板方法(與類的模板參數無關)作爲成員,我可以在類定義之外定義該方法嗎?如果是這樣,語法是什麼?模板類的模板成員方法可以定義在類定義的外部

如果在模板化類定義中定義了模板化方法,則一切正常。但是爲了在類之外定義方法,我嘗試了很多關鍵字和尖括號的組合,並且我總是得到編譯器錯誤(Visual Studio 2012)。

這裏的問題,歸結:

template <typename T> 
class TestClass 
{ 
    public: 
     // ctor 
     TestClass(T classtype) {m_classtype = classtype;} 

     // The declaration/definition below is fine. 
     template <typename U> void MethodOk(U param) {printf("Classtype size: %d. Method parameter size: %d\n", sizeof(m_classtype), sizeof(param));} 

     // The declaration below is fine, but how do I define the method? 
     template <typename U> void MethodProblem(U param); // What is the syntax for defining this outside the class definition? 

    private: 
     T m_classtype; 
}; 

回答

5
template<typename T> 
template<typename U> 
void TestClass<T>::MethodProblem(U param) 
{ 
    //... 
} 
+0

真棒,謝謝! –

1

只是把它當作嵌套模板,它們分別是:

template <typename T> 
template <typename U> 
void TestClass<T>::MethodProblem(U param) 
{ 
} 
+2

你錯過了:: :: – David

+0

真棒,再次感謝。 –