That is ADL (Argument Dependent Lookup) or Koenig Lookup (for the designer of the feature). The purpose of the feature is that in many cases the same namespace will contain types and functions that can be applied to those types, all of which conform the interface. If ADL was not in place, you would have to bring the identifiers into scope with using
declarations or you would have to qualify the calls.
This becomes a nightmare since the language allows for operator overloads. Consider the following example:
namespace n {
struct test {};
test operator+( test, test const & ); // implemented
};
int main() {
n::test a,b;
n::test c = a + b; //without ADL: c = n::operator+( a, b )
}
While it might seem like an awkward situation, consider that n
might be the std
namespace, test
might be ostream
, and operator+
could be operator<<
:
int main( int argc, char** ) {
std::cout << "Hi there, there are " << argc << " arguments" << std::endl;
}
Without ADL, the calls to operator<<
would have to be explicit, and moreover you would have to know which of them is implemented as a free function versus a method. Did you know that std::cout << "Hi"
is calling a free function and std::cout << 5
is calling a member function? Not many people realize it, and seriously, almost no one cares. ADL hides that from you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…