-5
#include<bits/stdc++.h>
using namespace std;

template <typename T1, typename T2> 
inline T1 max (T1 const& a, T2 const& b) 
{ 
    return a < b ? b : a; 
} 

template <> 
inline int max<int,int> (const int& a, const int& b)
{
    return 10;
}

int main() {
    cout << max(4,4.2) << endl;
    cout << max(5,5) << endl;
    return 0;
}

The output for the above code is 4 5 and not 4 10, please explain why.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
ashwath s
  • 51
  • 4
  • 9
    Is there a [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) hiding in your real code? You may be discovering one of the reasons that's a terrible idea. – Drew Dormann Mar 21 '22 at 15:24
  • 2
    Probably you are calling `std::max` instead of your `max` function. Without `using namespace std;` it works as intended: [Try it online!](https://tio.run/##bY3hioMwEIT/71MMHBSFtFyl/aPBvkRfIMZwBOIqusIdpc/uJfYO/dGFZZmdYT47DEcbDH8ty4dnG@bWQft@ktGZriYS1w3BSHzKz@DYdA73s8ImihrkOXhOBjrzjSxe2/MkBxgVA/@iyUEPEOKMTuaRYaDR4Ba3hKlAT@yBW7FnSc06XhW3RrZWpv/K2Kkmp8cecf6s6En0avCc5XjZk7RlaftZoHXqzi7qcirypFbLcRuq98mrur7L/QETb1l@AQ "C++ (clang) – Try It Online") – Pablochaches Mar 21 '22 at 15:28

1 Answers1

2

using namespace std; will make all names from the standard library namespace std visible to unqualified name lookup as if they were defined in the global namespace.

This includes the function std::max which has an overload of the form

template<typename T>
const T& max(const T&, const T&);

This overload is chosen for your call max(5,5) with T=int since it is more specialized than your function template with two different template parameters.

This is exactly the reason that using namespace std; is not recommended. Instead write only using declarations for the names you want imported, e.g.

using std::cout;
using std::endl;

or always qualify all standard library names with std:: when used.

user17732522
  • 53,019
  • 2
  • 56
  • 105