1

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.

  • max returns bool not T – michelson Nov 10 '18 at 18:17
  • 1
    Get rid of `using namespace std;` and you won't clash with [std::max](https://en.cppreference.com/w/cpp/algorithm/max). – Jesper Juhl Nov 10 '18 at 18:24
  • @michelson It most certainly does *not*. – Jesper Juhl Nov 10 '18 at 18:26
  • 1
    Or stop naming your functions `max` or `min`, or anything else that sounds generic. There is a good chance that using these often-used names as identifiers will lead to a name clash somewhere, whether it is in the standard headers, or some third-party code that isn't yours. – PaulMcKenzie Nov 10 '18 at 18:28

2 Answers2

4

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? .

Quimby
  • 17,735
  • 4
  • 35
  • 55
2

using namespace std; is the issue

Please stop using that, see why

The iostream header includes another header file that pulls std::max, giving a compiler error.

P0W
  • 46,614
  • 9
  • 72
  • 119