[英]overloading error for C++ template function
我正在嘗試對函數模板進行一些練習,如以下示例所示:
#include <iostream>
using namespace std;
template <class T>
T max(T a, T b)
{
return a > b ? a : b;
}
int main()
{
cout << "max(10, 15) = " << max(10, 15) << endl;
retun 0;
}
但是我遇到了以下錯誤。 有人能認出問題出在哪里嗎?
..\src\main.cpp:59:40: error: call of overloaded 'max(int, int)' is
ambiguous
cout << "max(10, 15) = " << max(10, 15) << endl;
^
..\src\main.cpp:16:3: note: candidate: 'T max(T, T) [with T = int]'
T max(T a, T b)
^~~
In file included from c:\mingw\include\c++\8.1.0\bits\char_traits.h:39,
from c:\mingw\include\c++\8.1.0\ios:40,
from c:\mingw\include\c++\8.1.0\ostream:38,
from c:\mingw\include\c++\8.1.0\iostream:39,
from ..\src\main.cpp:9:
c:\mingw\include\c++\8.1.0\bits\stl_algobase.h:219:5: note:
candidate: 'constexpr const _Tp& std::max(const _Tp&, const _Tp&)
[with _Tp = int]'
max(const _Tp& __a, const _Tp& __b)
抱歉,我不熟悉模板。 謝謝你的幫助。
您對模板的用法是正確的,但是編譯器抱怨已經有一個名為max
且具有相同參數的函數。
它的全名會std::max
,而是因為你寫的using namespace std
它只是max
和編譯器無法知道調用哪個函數。
解決方案是不使用using
,請參閱為什么將“使用命名空間std”視為不良做法? 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.