Search code examples
c++namespacesargument-dependent-lookup

Functions with class arguments are leaked from a namespace?


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 should not.

Consider this:

namespace name
{
  class C
    {
      int a;
    };

  void f(C c);
  void g(int a);
}

int main(int argc, char** argv)
{
  name::C c;

  name::f(c); 
  f(c);  // <--- this compiles, strangely enough

  name::g(42);
  // g(42);  <--- this does not, as I expected
}

The class argument from the same namespace causes the function f to 'leak' out of the namespace and be accessible without name::.

Does anybody have an explanation for this? It is certainly me and not the compiler being wrong here.


Solution

  • It's called argument-dependent lookup (or Koenig lookup). In short, the compiler will look for the function in namespaces that are the namespaces of argument types.