ostream operator << in Namespace hides other ostream::operator

This question already has an answer here:

  • Calling a function overloaded in several namespaces from inside one namespace 3 answers

  • 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

    上一篇: 当运算符<<重载时,std :: endl是未知类型

    下一篇: 命名空间中的ostream运算符<<隐藏了其他ostream ::运算符