Available Namespaces

There are three main namespaces.

  • std

    The ISO C++ standards specify that "all library entities are defined within namespace std." This includes namespaces nested within namespace std, such as namespace std::tr1.

  • abi

    Specified by the C++ ABI. This ABI specifies a number of type and function APIs supplemental to those required by the ISO C++ Standard, but necessary for interoperability.

  • __gnu_

    Indicating one of several GNU extensions. Choices include __gnu_cxx, __gnu_debug, __gnu_parallel, and __gnu_pbds.

A complete list of implementation namespaces (including namespace contents) is available in the generated source documentation.

namespace std

One standard requirement is that the library components are defined in namespace std::. Thus, in order to use these types or functions, one must do one of two things:

  • put a kind of using-declaration in your source (either using namespace std; or i.e. using std::string;) This approach works well for individual source files, but should not be used in a global context, like header files.

  • use a fully qualified name for each library symbol (i.e. std::string, std::cout) Always can be used, and usually enhanced, by strategic use of typedefs. (In the cases where the qualified verbiage becomes unwieldy.)

Using Namespace Composition

Best practice in programming suggests sequestering new data or functionality in a sanely-named, unique namespace whenever possible. This is considered an advantage over dumping everything in the global namespace, as then name look-up can be explicitly enabled or disabled as above, symbols are consistently mangled without repetitive naming prefixes or macros, etc.

For instance, consider a project that defines most of its classes in namespace gtk. It is possible to adapt namespace gtk to namespace std by using a C++-feature called namespace composition. This is what happens if a using-declaration is put into a namespace-definition: the imported symbol(s) gets imported into the currently active namespace(s). For example:

namespace gtk
  using std::string;
  using std::tr1::array;

  class Window { ... };

In this example, std::string gets imported into namespace gtk. The result is that use of std::string inside namespace gtk can just use string, without the explicit qualification. As an added bonus, std::string does not get imported into the global namespace. Additionally, a more elaborate arrangement can be made for backwards compatibility and portability, whereby the using-declarations can wrapped in macros that are set based on autoconf-tests to either "" or i.e. using std::string; (depending on whether the system has libstdc++ in std:: or not). (ideas from Llewelly and Karl Nelson)