Why was argument dependent lookup (ADL) invented? Is it just so we can write cout << stuff
instead of std::operator<<(cout, stuff)
? If that is the case, why wasn't ADL limited to operators instead of all functions?
Could the introduction of ADL have been prevented if C++ had had some other way to do generic output of both built-in and user-defined types, for example a type-safe printf
via variadic templates?
ADL was invented to allow the Interface Principle:
The Interface Principle
For a class X, all functions, including free functions, that both
are logically part of X, because they form part of the interface of X.
Check out Herb Sutter's excellent Guru of the Week on the topic.
If that is the case, why wasn't ADL limited to operators instead of all functions?
Why limit it artificially? ADL may be tricky to implement (when combined with C++’ overloading rules)1 but it’s an extremely useful technique. For one thing, the fact that it also works on functions makes it much easier to use other namespaces without importing the whole namespace.
Case in point, the SeqAn library:
using seqan::String;
String<Char> url = "http://www.seqan.de/";
std::cout << "The URL " << url << " has length " << length(url) << std::endl;
Notice that I’ve used the function seqan::length
without qualifying its full name. ADL finds it anyway. The SeqAn library uses such namespace-scope functions excessively and prefixing every usage with the namespace name would be impractical. Likewise, importing the namespace often isn’t advisable.
The same is of course true for many other libraries, such as most of Boost’s.
1 And I believe that this wasn’t immediately realized by the committee.
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