Tristan Brindle Tristan Brindle - 3 months ago 8
C++ Question

Why aren't C++14 standard-defined literals in the global namespace by default?

C++14 includes standard-defined literals for, amongst other things,

std::string
and various timespans from the
<chrono>
header.

To use them you must say
using namespace std::literals;
(or some variation depending on exactly which literals you want, as they're in a variety of inline namespaces).

All this is good, but I'm curious as to why the
using
declaration is required. UDLs without a leading underscore are reserved for the implementation, so there is no possibility that
"hello world"s
could ever mean anything else in a standard-conforming programme.

So why isn't
#include <string>
sufficient to bring the literal conversion function into scope? Why must I explicitly include the literal namespace?

EDIT: N3531 is the most recent version of the proposal I could find -- unfortunately it doesn't discuss the motivation for putting things in a namespace but only says:


One can summarize the requirements of the [Portland] discussion as follows:


  • use an inline namespace for a (group of related) UDL operator(s)



Answer

Because it easily generates conflicts, since the name is a single character. In fact, there already are two UDLs named s: One for strings and one for seconds. The problem is that at some stage, we are forced to either use unfitting, longer suffixes, or introduce namespaces in hindsight, which are both messy options.

So it was decided that UDLs are put into inline namespaces, which allow for unambiguous using directives (using namespace std::literals::chrono_literals) and simple directives (using namespace std).