Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I able to use the names in the std namespace even though I'm "using namespace std;"?

Isn't there already a max function in the algorithm header file? And by using namespace std;, I'm importing the function to the global namespace (which takes to arguments, and in this case both would be integers, so it shouldn't be an overload).

So why isn't there any naming conflict?

#include <iostream>
#include <algorithm>

using namespace std;

int max(int a, int b)
{
    return (a > b) ? a : b;
}

int main()
{
    cout << max(5, 10) << endl;
}
like image 674
Amirreza A. Avatar asked Dec 23 '22 15:12

Amirreza A.


1 Answers

So why isn't there any naming conflict?

You're declaring a non-template max, and std::max is a set of overloaded function templates, so they're all overloaded. And the non-template version declared in the global namespace is selected in overload resolution here.

F1 is determined to be a better function than F2 if implicit conversions for all arguments of F1 are not worse than the implicit conversions for all arguments of F2, and

...

  1. or, if not that, F1 is a non-template function while F2 is a template specialization

...

like image 152
songyuanyao Avatar answered Jan 17 '23 16:01

songyuanyao