3

I've came accross a strange namespace scoping behavior (using g++ 4.8.2). To explain the problem I've extracted a minimal code that reproduces this strange behavior:

namespace Weird {
  template <typename T>
    struct Rec
    {
      T val;
      Rec( T const& _val ) : val( _val ) {}
    };

  template <typename T>
    Rec<T>
    foo( Rec<T> const& r )
    {
      return Rec<T>( r.val * 2 );
    }

};

Weird::Rec<double>
bar( Weird::Rec<double> const& _input )
{
  return foo( _input );
}

In this code I would have expect G++ to complain about "foo" not being defined in the scope of "bar", which is not the case; the code just compiles fine.

So I'm a bit confused. Is g++ wrong (namespace leak)? Or if not, according to which mechanism does "foo" becomes visible in "bar" ?

1 Answers1

9

That's argument-dependent lookup (ADL), also known as Koenig lookup.

In short, use of an operator or unadorned function call will find names in the enclosing namespaces of the operands or arguments.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Thanks for your answer. I now understand this is legal. Nevertheless, though it seems convenient, I'm pretty sure this can lead to obscure bugs. I would prefer being forced to prefix with Weird:: in this case. – Yves Lhuillier Jun 19 '15 at 07:35
  • 1
    @YvesLhuillier if there is any ambiguity the program will fail to compile. – ecatmur Jun 19 '15 at 09:17