Learning Hub Search Ctrl K

Legacy C++ › 4. Templates and Namespaces

Namespaces

Organizing names, using-declarations and the ADL rules.

beginner #namespaces#using#adl#name-lookup

Explanation

A namespace groups names to avoid collisions: std::string, mylib::string. Namespaces are open: you can reopen and extend them in several files.

  • Qualified name: std::cout.
  • using-declaration: using std::cout; brings in one name.
  • using-directive: using namespace std; brings in all names. Fine in a small .cpp, harmful in a header.
  • Unnamed namespace: namespace { int helper; } gives internal linkage; the modern replacement for file-level static.
  • Namespace alias: namespace fs = boost::filesystem;.
  • ADL (argument-dependent lookup): when calling an unqualified function, the compiler also searches the namespaces of the argument types. That is why swap(a, b) finds mylib::swap for mylib::Widget, and std::cout << x finds the right operator<<.

Example

#include <iostream>
#include <string>

namespace geometry {
    struct Point { double x, y; };

    double distance(const Point& a, const Point& b) {
        double dx = a.x - b.x, dy = a.y - b.y;
        return dx * dx + dy * dy;               // squared distance, for brevity
    }

    namespace detail {                          // nested namespace
        inline int version() { return 2; }
    }
}

namespace {                                     // private to this file
    int callCount = 0;
}

namespace g = geometry;                         // alias

int main() {
    geometry::Point a = {0, 0}, b = {3, 4};
    std::cout << geometry::distance(a, b) << "\n";   // 25
    std::cout << distance(a, b) << "\n";             // ADL finds geometry::distance
    std::cout << g::detail::version() << "\n";

    using std::string;                               // one name only
    string s = "ok";
    ++callCount;
    std::cout << s << callCount << "\n";
    return 0;
}

Common pitfalls

  • using namespace std; in a header pollutes every file that includes it and invites name clashes.
  • Ambiguity when two using namespace directives bring in the same name.
  • A function defined in the wrong namespace compiles but is not the one declared in the header, giving an “unresolved external” at link time.
  • Putting main inside a namespace is not allowed (it must be global).
  • ADL can pick an unexpected function; qualify the call to avoid it.

Legacy vs modern

C++11 adds inline namespace (versioning) and C++17 allows nested definitions: namespace a::b::c { }.

Exercises

1. How do you reach the global counter when a local also named counter hides it?

::counter, the scope-resolution operator with an empty left side.