What is Koenig lookup?
– Wikipedia
– Exceptional C++ by Herb Sutter
Simply stated, Koenig lookup can be regarded as finding a method/function from the namespace where a argument resides. For example, consdier the following:
namespace NS { struct X { }; f(X); } int main() { f(NS::X); return EXIT_SUCCESS; }
In this code, we mentioned that X is declared at NS. Hence, the C++ languge tries to find the definition of the function f from NS. That’s what Koenig means. At first glance, this behaviors seems to be counter-intuitive, but it’s not as you can see from the following (After What’s In a Class? – The Interface Principle):
#include
#include
int main()
{
std::string msg = “Hello World”;
std::cout << msg << std::endl;
return EXIT_SUCCESS;
}
[/code]
If it were not for Koenig lookup, it's not possible to lookup operator<< declared in std. Do you get it? cout and endl can be specified as ones in std namespace, while << operator can't. However, because the given parameter is std::string, a compiler tries to find operator<< which is declared at std. In this way, << works.