C++ operator lookup rules / Koenig lookup

Operator overloading is like a function but differs, and one of the differences is namespace lookup.

Like functions, operator overloads belong in a namespace, but scoping the way you scope a function would be impractical. Imagine if your code had to call

std::cout thesus::core::<< p; // ouch and obviously incorrect syntax

Therefore the << operator must be in the namespace of one of the parameters, either std (for the cout) or the namespace of the p, in this case thesus::core.

This is the Koenig Lookup principle. You must define the operator overload in the correct namespace.


In argument dependent lookup (the correct name for koenig lookup) the compiler adds to the overloaded function set the functions which are declared in the namespaces of each parameter.

In your case, the first operator<< is declared in the namespace thesus::core, which is the type of the argument you call the operator with. Therefore this operator<< is considered for ADL because it's declared in an associated namespace

In the second case, the operator<< seems to be declared in the global namespace which is not an associated namespace as parameter one is of type from namespace std and param 2 is of type from namespace theseus::core.

Actually, probably your 2nd operator<< isn't declared in global namespace as that would be found through looking in parent scopes.. maybe you've got something more like this? If you can post more code we can give a better answer.


Ok I remembered, ADL doesn't lookup in parent scopes when it finds a name in the current scope. So the boost macro BOOST_TEST_MESSAGE expands to include an operator<< and there is some in the scope tree a non-viable operator<< between the expression and global scope. I updated code to illustrate this (hopefully).

#include <iostream>

namespace NS1
{
  class A
  {};

  // this is found by expr in NS2 because of ADL
  std::ostream & operator<<(std::ostream &, NS1::A &);
}


// this is not seen because lookup for the expression in NS2::foo stops when it finds the operator<< in NS2
std::ostream & operator<<(std::ostream &, NS1::A &);

namespace NS2
{
    class B
    {};

    // if you comment this out lookup will look in the parent scope
    std::ostream & operator<<(std::ostream &, B &);

    void foo(NS1::A &a)
    {
        std::cout << a;
    }  
}