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