2013-02-08 42 views
11

我需要專門研究C++中的函數模板。不帶參數的函數的模板專業化

template<typename T> 
void doStuff<T>() {} 

template<> 
void doStuff<DefinedClass>(); 

template<> 
void doStuff<DefinedClass2>(); 

我想這是不正確的語法(因爲它不是編譯)。我應該怎麼做?
另外,因爲我將不會在doStuff<DefinedClass>中定義模板參數,是否可以在.cpp中聲明主體?

注意:doStuff將使用T wihtin來聲明一個變量。

+1

當你說「它不是編譯」,你應該包括相關的錯誤信息。 –

+0

'template void doStuff (){}'甚至編譯在第一位(我認爲這個''是無效的)。 –

回答

12

主模板沒有獲得第二對模板參數。只是這樣的:

template <typename T> void doStuff() {} 
//      ^^^^^^^^^ 

只有專業化既有template <>在前面和名稱後<...>,如:

template <> void doStuff<int>() { } 
+0

謝謝,但仍然無法正常工作。如果我寫了如下的專業化:「template <> void doStuff();」我得到:「無效顯式專業化」>'令牌' –

+0

如果我把「模板」我得到「template-id'buildBom '在主模板聲明」 –

+2

不,它應該是'template <> void doStuff ();'專門化和'模板 void doStuff();'一般情況下... – Synxis

4

用於主模板正確的語法是:

template <typename T> 
void doStuff() {} 

要定義專業化,請執行以下操作:

template <> 
void doStuff<DefinedClass>() { /* function body here */ } 
2

我想這不是正確的語法(因爲它不是編譯)。我應該怎麼做? doStuff將使用T wihtin其身體來聲明一個變量。

template<typename T> 
void doStuff() 
{ 
    T t = T(); // declare a T type variable 

} 

纔有可能宣佈身在一個.cpp?

C++只支持inclusive mode,您不能單獨編譯然後再鏈接。

從評論,如果你想爲專業型int

template<> 
void doStuff<int>() 
{ 
}