2016-03-03 91 views
3

我有類模板方法:模板法實施<>

template<class T> 
    A& doSomething(T value) 

然後,我有一個實現

template<class T> 
    A& A::doSomething(T value){ 
     // do something with value 
     return *this; 
    } 

然後,我有一個專門用於讓說布爾

template<> 
    A& A::doSomething(bool value){ 
     // do something special with value of type bool 
     return *this 
    } 

這是我明白,現在在代碼中有這樣的東西,我不知道什麼意思:

template A& A::doSomething(char const*); 
template A& A::doSomething(char); 
template A& A::doSomething(int); 
template A& A::doSomething(int*); 
template A& A::doSomething(double); 
... 

這些最後5行模板的確切含義是什麼?

謝謝

回答

5

這是Explicit instantiation,這迫使模板的實例與指定的模板參數,並防止它們的隱式實例。

顯式實例化定義強制實例化它們引用的函數或成員函數。它可能出現在 程序中的模板定義之後,並且對於給定的 參數列表,只允許在程序中出現一次。

的顯式實例聲明(一個外部模板)防止 隱式實例:否則將導致 隱式實例必須使用在程序中提供其他地方的顯式實例 定義的代碼。

而看到Explicit instantiation - when is it used?


因爲你標記的C++ 03,請注意,在鏈接頁面中提到extern template從C++ 11引入的。

+0

沒有標準'extern'模板C++ 03 – Garf365

+0

@ Garf365添加到答案。 – songyuanyao

+0

謝謝,現在我明白了。我認爲這個用例是爲了避免在鏈接到在cpp文件中實現其模板的庫時的未定義引用。我對嗎? – Jan

2

這行不是執行。這裏只說編譯器「創造」代碼doSomething的類型char const*charintint *double

template A& A::doSomething(char const*); 
template A& A::doSomething(char); 
template A& A::doSomething(int); 
template A& A::doSomething(int*); 
template A& A::doSomething(double);