FAQ 15.06 What is name lookup?

graphics/new_icon.gif

Name lookup, sometimes known as Koenig lookup, is a clever solution to a difficult problem. Consider the problem of printing a string in the following example.

 #include <iostream> #include <string> void sample() throw() {   std::string s = "hello world";   std::cout << s;                                    <-- 1 } 

(1) How does the compiler find the proper <<?

The operator<< that's needed is a non-member function that takes a string as a parameter and is packaged with the string class. How is the compiler supposed to find the proper operator? One approach is to make all the names in the entire standard namespace accessible without qualification (e.g., using namespace std;), but this is an ugly solution that is discussed in FAQ 15.09. An equally ugly alternative is to change sample() to the following:

 void sample2() throw() {   std::string s = "hello world";   std::operator<< (std::cout, s);                    <-- 1 } 

(1) Ugly

Koenig lookup is a better alternative. It recognizes that non-member functions associated with a parameter class such as string can be thought of as part of an extended public: interface, and there is no harm in having the compiler automatically look for such functions in the same namespace as the parameter class. This is the technique known as name lookup, and it allows the example above to work "as is." The trick is that a class parameter, in this case string, somehow identifies a namespace, in this case std, and then all the non-member functions that refer to that parameter class are automatically made available. It's a pretty slick idea that usually simplifies life.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net