简体   繁体   中英

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;
}

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

...

And by using namespace std I'm importing the function to the global namespace

This is a common misconception. Nothing is imported. In fact, placing the directive using namespace std; in the global namespace means that when a name is looked up in the global namespace, that name is also looked up in namespace std .

The std::max function is still in the namespace std , it is not in the global namespace.

Your declaration of max is fine as you are declaring ::max which is a separate entity to std::max .

When you make the unqualified function call max , the name is looked up in the global namespace, and also in namespace std .

The results of both of those lookups lead to an overload set consisting of all signatures of functions called ::max and std::max .

Then overload resolution selects the best match out of the overload set for the arguments provided, and it turns out that ::max is a better match because a non-template function is a better match than a function template, all other things being equal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM