2014-11-21 29 views
0

我剛開始學習模板編程。我知道可以用兩種方式實例化一個函數模板,這兩種方法都是expilicit和implicit。考慮下面的代碼。零參數函數模板顯式實例化似乎不起作用

template <typename var> 
void cool(){ 
    var y = 45; 
    int i = 2; 
} 

template void cool<int>(); // instantiated here 

int main(){ 
    cool(); // error no matching function call. why? 
    cool<int>(); // works. whats the difference between both? 
    return 0; 
} 

當我使用的無參數的函數模板,我得到error: no matching function call for cool()甚至當我明確實例化。但這種情況並非如此,當我使用的參數如下圖所示

template <typename var> 
void cool(var x){ 
    var y = 45; 
    int i = 2; 
} 

template void cool<int>(int); // instantiated here 

int main(){ 
    cool(24); // works 
    return 0; 
} 

我明白了明確instantation工作,只有當函數的參數有模板類型。如果函數的參數列表中沒有模板類型,它將被忽略。是對的嗎?或者有什麼我錯過了。任何幫助表示讚賞。

回答

2

顯式實例化並不能讓編譯器猜測模板參數應該是什麼。此外,請考慮:

template <typename var> 
void cool(){ 
    var y = 45; 
    int i = 2; 
} 

template void cool<int>(); 
template void cool<char>(); 

int main() 
{    // now, even if explicitions specializations did 
       // what you think they do, 
    cool(); // what should var be here, int or char? 
} 

顯式實例化只是強制實例化,以便在其他地方只能使用聲明。如果無法推斷模板參數,則需要明確指定它們。

這就是爲什麼你的第二個例子起作用,模板參數可以從調用中推導出來。顯式專業化與它無關,你可以刪除它,它也可以工作。

1

你不能實例化一個沒有參數的單參數模板。參數有時可以推導出,所以你不需要明確提供,但你仍然需要提供它們。然而,在你的情況下,模板參數都是可以被忽略的(因爲它們都不是函數參數類型的一部分),所以你必須自己指定所有的參數。