Reputation: 77
I am trying to do some practice with function templates as in the following example:
#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;
}
But I got the following errors. Could anybody recognize where the problem is?
..\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)
I am sorry I am new to templates. Thanks for your help.
Upvotes: 1
Views: 146
Reputation: 19213
Your usage of templates is correct, but the compiler complains that there already is a function called max
with same arguments.
It's full name would be std::max
, but because you wrote using namespace std
its just max
and compiler cannot know which function to call.
Solution is not to use using
, see Why is "using namespace std" considered bad practice? .
Upvotes: 4