Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was argument dependent lookup invented?

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?

like image 761
fredoverflow Avatar asked Nov 25 '10 11:11

fredoverflow


2 Answers

ADL was invented to allow the Interface Principle:

The Interface Principle

For a class X, all functions, including free functions, that both

  • "mention" X, and
  • are "supplied with" X

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.

like image 103
Daniel Lidström Avatar answered Sep 20 '22 18:09

Daniel Lidström


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.

like image 23
Konrad Rudolph Avatar answered Sep 18 '22 18:09

Konrad Rudolph