0

I always thought that calling a function in a namespace requires either a using declaration, or a fully qualified name.

This code, however, compiles fine. It appears that the parameter from the namespace does the magic. Can anyone explain why this exception from the rule?

#include <iostream>

namespace A {

class B {};

void f(const B&)
{
  std::cout << "f\n";
}


} // A


int main(int argc, char* argv[])
{
  A::B b;
  f(b);
  return 0;
}
Photon
  • 3,182
  • 1
  • 15
  • 16
  • 1
    Search for ADL in SO. There are lots of questions. Not sure which one will address your question. – R Sahu Jan 06 '15 at 22:36
  • 1
    [Argument dependent lookup.](http://en.wikipedia.org/wiki/Argument-dependent_name_lookup) – David G Jan 06 '15 at 22:36
  • 1
    ADL is one of the reasons `std::cout << "something"` (which is the same as `operator<<(std::cout, "something")` works. `operator<<` is not defined in the global namespace, but because `std::cout` is one of its parameter belonging to `namespace std`, ADL does the magic and searches for `operator<<` inside `namespace std`. – vsoftco Jan 06 '15 at 22:42
  • @vsoftco - It makes sense, but the operator<< could also be implemented as a member function of std::ostream, which would make this feature unneeded. I'm sure there are other examples, though. – Photon Jan 07 '15 at 06:46

0 Answers0