About Me

My photo
Bangalore, Karnataka, India

Wednesday, June 21, 2006

Koenig lookup

Recently I was stumbling on the Net and found this term Koenig Lookup and was totally stumped.

Now what in the world does Koenig Lookup mean (ofcourse with respect to C++ !! ).

Koenig Lookup specifies how unqualified functions are resolved based on the namespaces to which the parameters belong.

Did that give any idea ? I knew that wouldn't. ;-)

Ok. So let me show it to you with a neat example.

Consider a namespace

namespace NS
{
class myclass
{ ... // some data members and member methods.
};

void operationOnMyClass(myclass& c);
}

int main(int argc, char* argv[])
{
NS::myclass obj;
operationOnMyClass(obj);
}



Under normal circumstances of resolving the non-member function operationonMyClass, the global namespace would be searched for a definition for operationOnMyClass. Since there is no implementation in global namespace it will fail.


Instead the compiler can be a little bit more intelligent where in it knows that the function parameter belongs to namespace NS. Hence it also searches the namespace NS apart from the global namespace. Hence it finds the correct implementation for operationOnMyClass.

This lookup using namespace information is known as Koenig lookup. This feature is also known as Argument Dependent Lookup(ADL) or Argument dependent name lookup.

This is exactly how the operator << gets resolved to STL namespace when using
std::cout << "Found the implementation !";

The std::cout being the first parameter to the operator << method , the compiler searches the namespace stl and finds the implementation.

Thats all for now. Will be back with more such intricate tricks of C++ later.

1 comment:

DK02 said...

Nice stuff!!