Possible Duplicate:
What is "Argument-Dependent Lookup" (aka ADL, or "Koenig Lookup")?
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:
std::complex<double> c, d; c += d; // wouldn't really work without ADL
or the ubiquitous iostream operators:
std::string s("hello world"); std::cout << s << std::endl; // Hello world would not compile without ADL...
For fun, this is what hello world would look like without ADL (and without using
keyword...):
std::string s("hello world"); std::operator<<(std::cout, s).operator<<(std::endl); // ugly!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With