简体   繁体   中英

Why is operator""s hidden in a namespace?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM