Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why are parts of the standard library in a separate namespace

Tags:

c++

Why are some parts of the C++ standard library (and it seems like in more recent standards it is getting more common) not directly in the ::std namespace, but rather in a nested namespace? std::chrono and std::filesystem are two examples that pop to mind.

like image 696
Baruch Avatar asked Jan 18 '18 15:01

Baruch


1 Answers

The obvious reason is the same as for any other project: there would be name collisions without it. For example, std::filesystem::copy vs. std::copy.

This isn't a complete explanation though, because

  • I can't immediately see any collisions in the std::chrono namespace
  • the committee could just have chosen a non-conflicting name instead

More convincingly,

  1. these libraries are based on their Boost predecessors, because those have proved to be useful and are well-tested. That means there's existing code using them, and it's easier to port that code to the C++11 versions if the namespace structure doesn't change, and no new conflicts are introduced.
  2. more broadly, C++ best practice has evolved since the first version of the standard library.

Note that (as Default points out in a comment), the regex library chooses consistency with Boost over namespace best practice, so it seems like #1 is more important. The same is true for std::thread etc.


Separating the factual from the speculative and hypothetical:

  • The discussed libraries are based on Boost predecessors
  • The discussed libraries keep the namespace structure of their Boost predecessors
  • The discussed libraries' namespace structures are not consistent among themselves (or with the rest of the standard library)
  • Changing namespace structure in C++, even without name collisions, can have side-effects related to ADL (so it isn't a trivial search-and-replace)

Conclusion: the namespace structure was chosen for consistency with Boost, rather than consistency with the rest of the standard library or even among the libraries added in C++11.

like image 130
Useless Avatar answered Oct 19 '22 03:10

Useless