ostream operator << in Namespace hides other ostream::operator
This question already has an answer here:
As stated here, this is an example of name hiding. By defining operator<<
in namespace MyNamespace
all the definitions from the higher namespaces (like global) are hidden.
Note that as stated here:
[...]this feature doesn't interfere with Koenig lookup [...], so IO operators from std::
will still be found.
(details about Koenig lookup)
The solution is to refer to the overload in the other namespace with the using
directive, as described here and here. This was mentioned in the comments by Michael Nastenko.
Thus using ::operator<<;
, with ::
referring to the global namespace.
Thus the code will become:
#include <string>
#include <iostream>
typedef std::pair<std::string, std::string> StringPair;
std::ostream& operator<<(std::ostream& os, const StringPair &pair) {
os << pair.first << '.' << pair.second;
return os;
}
namespace MyNamespace {
class MyClass {};
using ::operator<<;
std::ostream& operator<< (std::ostream&, const MyClass &);
void xxx();
}
void MyNamespace::xxx() {
StringPair pair("1","2");
std::cout<<pair<<std::endl;
}
int main() {
MyNamespace::xxx();
return 0;
}
example on Coliru
链接地址: http://www.djcxy.com/p/73074.html