0

Take a look at this simple snippet:

namespace Test
{
    struct A {};
    void foo( A _a ) {}
}


int main( int, char** )
{
    foo( Test::A() ); // 1. why foo doesn't require Test:: ?
    Test::foo( A() ); // 2. why A() requires Test:: considering above line?

    return 0;
}

As mentioned in the source:

  1. foo( Test::A() ); why foo doesn't require Test:: here?
  2. Test::foo( A() ); why A() requires Test:: considering above line?

(Visual Studio 2008 and gcc4.8 give the same result, so I suppose this is standard behavior, but I'm wondering which part of standard defines it?)

Bogdan
  • 984
  • 8
  • 16

1 Answers1

2

This is Argument-dependent name lookup, a.k.a. Koenig lookup (although Andrew Koenig did not invent it). It is defined in the chapter of the same name in the standard.

It enables things like:

std::string str( "Hello world!" );
std::cout << str;

The overload operator<<( std::ostream &, std::string ) is in the std:: namespace -- and without ADL, it would not be found.

It works only for functions looked for in the namespace of their arguments, not the other way around (your example 2), which would further weaken namespace barriers with no comparable benefit to case 1.


More in-depth discussion of the subject here.

Community
  • 1
  • 1
DevSolar
  • 67,862
  • 21
  • 134
  • 209