2012-04-18 64 views
3

這段代碼有什麼問題?模板函數中的錯誤

#include <iostream> 
using namespace std; 

template <typename T> 
T max(T X, T Y) 
{ 
    return (X > Y) ? X : Y; 
} 

int main() 
{ 
    int x = max(5,6); 
} 

我收到此錯誤:

overload.C: In function 'int main()': 
overload.C:19: error: call of overloaded 'max(int, int)' is ambiguous 
overload.C:12: note: candidates are: T max(T, T) [with T = int] 
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2 /bits/stl_algobase.h:206: note:     const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int] 

回答

12

max標準庫已定義。刪除using namespace std,它應該工作。

+0

+1這裏是鏈接,僅供參考:http://en.cppreference.com/w/cpp/algorithm/max – 2012-04-18 09:34:04

+0

這太可笑了。爲什麼不能說清楚! :) – cppcoder 2012-04-18 09:34:31

+0

+1:但也許加一句關於標準不禁止標準頭文件到'#inc'其他標準頭文件,這會導致''蠕變。 – 2012-04-18 09:51:08

0

也許max已經由standrad庫聲明。儘量不要導入名稱空間。