Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)
like image 882
Tristan Brindle Avatar asked Oct 27 '14 14:10

Tristan Brindle


3 Answers

There already are two UDLs named s: one for strings and one for seconds. Due to the understandably terse names of suffixes, they chronically suffer from name conflicts, so pouring all of them into one namespace cannot go well for long. Hence it was decided that they be put into inline namespaces, which allow for both unambiguous (using namespace std::literals::chrono_literals) and simple using directives (using namespace std).

like image 132
Columbo Avatar answered Oct 30 '22 03:10

Columbo


the standard library already defines multiple versions of what s can mean:

  1. It can be used to define a string literal.
  2. It can be used to define a chrono::seconds literal.

One is based on a string literal, one is based on an integer or a double literal, of course, i.e., they can actually coexist. However, I'd expect that there may be more uses of s in the future. Thus, having to choose which namespaces are imported rather than getting any imposed on you seems like a reasonable approach.

like image 44
Dietmar Kühl Avatar answered Oct 30 '22 04:10

Dietmar Kühl


Look at paper N2765. UDLs are hooked into the regular name lookup process. As string literals have common string types, there's a large chance of a collision if you ignored namespaces.

like image 25
MSalters Avatar answered Oct 30 '22 02:10

MSalters