Functions with class arguments are leaked from a namespace?

前端 未结 4 1224
礼貌的吻别
礼貌的吻别 2021-02-02 11:14

I have a small piece of code here for your consideration which puzzles me quite a lot. The strange thing is that it compiles on both Sun Studio and GCC even though I think it sh

4条回答
  •  长情又很酷
    2021-02-02 11:47

    This is Argument-Dependent Name Lookup, a.k.a. ADL, a.k.a. Koenig lookup. This was invented to make operators work as expected, e.g.:

    namespace fu {
        struct bar { int i; };
        inline std::ostream& operator<<( std::ostream& o, const bar& b ) {
            return o << "fu::bar " << b.i;
        }
    }
    
    fu::bar b;
    b.i = 42;
    std::cout << b << std::endl; // works via ADL magic
    

    Without ADL you'd have to either explicitly bring the output operator with ugly using fu::operator<<;, or use even uglier explicit call:

    fu::operator<<( std::cout, b ) << std::endl;
    

提交回复
热议问题