Error: calling overloaded 'max (int, int) is ambiguous

#include <iostream> using namespace std; template<typename T> T max(T lhs, T rhs) { return lhs < rhs ? rhs : lhs; } template<> int max<int>(int lhs, int rhs) { return lhs < rhs ? rhs : lhs; } int main() { cout << max<int>(4, 5) << endl; } ~/Documents/C++/boost $ g++ -o testSTL testSTL.cpp -Wall testSTL.cpp: In function 'int main()': testSTL.cpp:18:24: error: call of overloaded 'max(int, int)' is ambiguous testSTL.cpp:11:5: note: candidates are: T max(T, T) [with T = int] /usr/include/c++/4.5/bits/stl_algobase.h:209:5: note: const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int] 

How to fix this error?

+6
source share
6 answers

All this because of your using namespace std; . Delete this line. Using this directive, you bring std::max (which must be somehow enabled via iostream) to the global scope. Therefore, the compiler does not know which max to call is ::max or std::max .

I hope this example will be a good scarecrow for those who think that the use of directives will be free. Strange mistakes are one side effect.

+19
source

I think the compiler cannot decide whether to use std :: max or your max, because you have the namespace std; and both your max and std :: max correspond to a vector

+5
source

You come across std::max() . Rename it to something like mymax and it will work.

+4
source

You have both max and std::max . The compiler does not know which one you would like to name.

You can say this by calling ::max(4,5) or std::max(4,5) , or - even better - not have using namespace std in the file.

+4
source

This is because the std :: max template function is defined. Remove "using namespace std" and add "std ::" where necessary, or use ":: max".

+3
source

The problem is that there is already a function called 'max' defined by std. To fix this, rename your function to something else, for example:

 #include <iostream> using namespace std; template<typename T> T mymax(T lhs, T rhs) { return lhs < rhs ? rhs : lhs; } template<> int mymax<int>(int lhs, int rhs) { return lhs < rhs ? rhs : lhs; } int main() { cout << mymax<int>(4, 5) << endl; return 0; } 
+2
source

Source: https://habr.com/ru/post/907397/


All Articles