Possible Duplicate:
Why does C++ parameter scope affect function lookup within a namespace?
Today I experienced this weird behavior. I can call strangeFn without using namespace Strange
first, but does not allow calling strangeFn2 Why?
namespace Strange
{
struct X
{
};
void strangeFn(X&) {}
void strangeFn2(int) {}
}
int main()
{
Strange::X x;
strangeFn(x); // GCC allows calling this function.
strangeFn2(0); // Error: strangeFn2 is not declared in this scope.
return 0;
}
How does C++ compilers resolve the scope of the symbols?
This is called Argument Dependent Lookup (or Koenig Lookup)
Basically, if a symbol couldn't be resolved, the compiler will look into the namespace(s) of the argument(s).
The second function call fails, because
strangeFn2
isn't visible in the current namespace, neither is it defined in the namespace of it's parameter type (int
)You can see how this works well with operator functions:
or the ubiquitous iostream operators:
For fun, this is what hello world would look like without ADL (and without
using
keyword...):There are shadowy corner cases with ADL and overload resolution in the presence of function templates, but I'll leave them outside the scope of the answer for now.