2011-11-10 40 views
4

我一直在嘗試理解模板專業化。這是爲什麼產生錯誤(specialization of 'T foo(T, T) [with T = int]' after instantiationC++中的模板專業化

template <class T> T foo(T a, T b); 

int main() 
{ 
    int x=34, y=54; 
    cout<<foo(x, y); 
} 

template <class T> T foo(T a, T b) 
{ 
    return a+b; 
} 

template <> int foo<int>(int a, int b) 
{ 
    cout<<"int specialization"; 
} 
+1

之前'main'只是移動的定義。 –

+1

坐在t雨閱讀thw問題與我的android手機,但不能夠及時回答HURTS –

+1

@ JohannesSchaub-litb你上癮!尋求幫助 ;) –

回答

8

該標準要求所有模板定義必須在實例化時知道的,每個翻譯單元看到相同的定義。否則你的程序不合格(實際上不需要診斷)。

(所以要解決這個問題,只是把所有模板定義在程序的頂部)。

記住,模板功能都沒有的功能,只是模板。將其視爲代碼生成工具。

3

的明確專門的模板功能foo()應該是可見的,纔可以被稱爲/實例化。

實際上,上述規則適用於所有模板功能。

解決方案:
移動爲foo()模板專業化的main()之前。

以下應該只是罰款:

template <class T> T foo(T a, T b); 

/*Should be visible before instantiation*/ 
template <> int foo<int>(int a, int b) 
{ 
    cout<<"int specialization"; 
} 

int main() 
{ 
    int x=34, y=54; 
    cout<<foo(x, y); 
} 

template <class T> T foo(T a, T b) 
{ 
    return a+b; 
} 
0

不要這樣做。

什麼香草薩特說:

如果你正在寫一個函數基本模板,寧願把它寫爲不應該被專業或 重載一個 單一功能的模板,然後執行函數模板完全作爲一個 簡單的切換到包含靜態函數的類模板,其中 具有相同的簽名。

參見:http://www.gotw.ca/publications/mill17.htm