Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
152 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...