Tuesday, April 17. 2007

C++ name lookup mechanism

In C++, you can use namespace to logically group names that belong together. If you use a name, the compiler uses an algorithm to derive the thing you mean by the name.

The compiler first tries to look up the name in the specified namespace (via the scope operator ::), the local scope, the class scope, the global scope or in namespaces included in these scopes with using declarations (like using Lexer::get_token) or with using directives (like using namespace Lexer).

Insight: If the compiler can't find the name, it does not give up yet. Instead she tries to find the name in the namespace of its arguments. For example this code snippet is valid C++ code:

#include <string>

namespace Chrono {
  class Date { };
  bool operator==(const Date&, const std::string&);
  std::string format(const Date&);
}

void f(Chrono::Date d, int i) {
  std::string s = format(d);     /* finds Chrono::format, because of the 
                                    namespace of its argument d */
  // std::string t = format(i);  /* does not work, as there is no 
                                    'format' in the global scope. */
}

I adapted the example from Bjarne Stroustrup's "The C++ Programming Language"). As a further reading, the gcc manual section Name lookup, templates, and accessing members of base classes describes the two stage name lookup that is used within templates.