1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <string>
std::ostream& operator<<(std::ostream& os, const std::string& str) {
os << '[';
std::operator<<(os, str);
os << ']';
return os;
}
int main() {
std::string str = "hi";
std::cout << str;
}
| |
In the above program, I define an operator<< function in global namespace which has exactly the same signature as the one define in <string> header :
http://www.cplusplus.com/reference/string/string/operator%3C%3C/ .
In the main function, I call operator<< on cout and a string, after which I guess it would cause ambiguity. The result is out of my anticipation, it compiles and prints [hi]. So I guess my function is a better match because it does not require argument-dependent lookup (ADL) (Please let me know if I'm wrong).
Moreover, even if I add using namespace std; at the beginning of the main function, the program still compiles and prints [hi].
In short, I have two question:
#1 : Why is my function a better match (therefore no ambiguity) in the two cases respectively (with and without using namespace std;)?
#2 : Does using namespace affect ADL? Is ADL still performed after applying using namespace, or is it not performed because the function is thrown into global namespace?
Thanks in advance.