Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to place operator ""s into std::literals::string_literals? [duplicate]

Tags:

c++

c++14

In order to use operator""s for std::string you have to do using namespace std::string_literals. But user-defined literals that don't begin with _ are reserved, so possible conflict can't be an excuse. The other operator""s is from std::chrono but that's for int literals, so there's no conflict there either.

What's the reason for this?

like image 395
user4375981 Avatar asked Nov 23 '22 01:11

user4375981


1 Answers

There are actually two reasons why literals are put into namespaces:

  1. It is considered undesirable that users would use using namespace std; just to get hold of the corresponding literals. Having the literals declared in namespaces specific to these doesn't cause the problem.
  2. Depending on the domain it may be desirable to use s as the suffix for something else. There is already another suffix s to mean seconds but they don't really conflict.

In the video of STL's CppCon 2014 talk (posted by remyable in a comment) Stephan T. Lavavej explains the overall design of the literals in C++14 and its pretty clear that they are not supposed to be in the global namespace! Instead, the literal suffixes in the standard library live in a hierarchy of inline namespaces giving users fine-grained control over the literals being made available. For example, the literal suffix for strings is declared like this (21.3 [string.classes] paragraph 1):

namespace std {
    inline namespace literals {
        inline namespace string_literals {
            string operator"" s(char const* str, size_t len);
        }
    }
}

This hierarchy of inline namespaces makes it possible for users to get the appropriate choice of literal suffixes:

  • using namespace std; - you get everything in the standard C++ library, including the literal suffixes, without any qualification.
  • using namespace std::literals; - you get all literal suffixes defined in the standard C++ library.
  • using namespace std::string_literals; - you get all literal suffixes applicable to strings.
  • using namespace std::literals::string_literals; - yes, you can do that but you really shouldn't: that's equivalent to using namespace std::string_literals;.

Clearly, the committee wouldn't have gone to that much effort if it had considered the idea viable to just pollute the global namespace with literal suffixes, although they can't even conflict with any user literal suffixes.

like image 194
Dietmar Kühl Avatar answered Nov 24 '22 14:11

Dietmar Kühl