2010-10-02 102 views
3
​​

爲什麼富(5)失敗,但富< int>的(5)工作?模板參數推導錯誤

+1

你認爲模板應該實例化的是什麼類型的T?在模板參數的情況下,僅僅因爲它沒有被使用並不意味着它不存在。 – 2010-10-02 16:55:34

+0

爲什麼'foo ();'不起作用。 – 2010-10-02 16:57:29

+2

@litb:我試着加大了你的刪除回覆。 :) – 2010-10-02 16:58:16

回答

3

編譯器不知道什麼是T.

0

如果你定義一個函數爲模板的功能,那麼你需要定義你要使用(即使你的函數不使用模板類型是什麼類型)

所以你需要告訴編譯器T是什麼類型。

4

您也許想寫

template <typename T> 
void foo(T i)   // note the type of i 
{ 
    //nothing inside 
} 

更新

下面是完整的代碼

#include <iostream> 
using std::cout; 

template <typename T> 
void foo(T i) { 
    cout << __PRETTY_FUNCTION__ << " called with " << i << "\n"; 
} 

int main() { 
    foo(5); 
    foo<int>(7); 
} 

輸出:

void foo(T) [with T = int] called with 5 
void foo(T) [with T = int] called with 7 
0

爲什麼foo(5)失敗,但是foo < int>(5)有效嗎?

因爲編譯器無法確定T是[來自foo(5)]。

只能離開結束的模板參數,而不是開始或中間:

例如:

template<typename T, typename U> 
void foo(T t) 
{ 
} 
template<typename T, typename U> 
void bar(U u) 
{ 
} 

int main() 
{ 
    foo<int>(5);  // Error!! Compiler cannot decide what `U` is 
    foo<int, int>(5); // Works!! 

    bar<int>(5);  // Works!! `U` deduced from `5` (int) 
    bar<int, int>(5); // Works!! 
} 
0

通常你有這樣的事情:

template <class T> 
void foo(T i) { } 

然後,當您通過一個int作爲參數時,編譯器可以推斷出T必須是int。由於您的代碼在任何地方都不使用T,因此編譯器無需繼續推導其結果。