使用`using namespace std::literals`是否安全?
using namespace std::literals Safe? Great question! The short answer is yes, this is generally safe—even in global scope, which is usually frowned upon for most using namespace directives. Let's break down why:
First, let's anchor this to the rules you mentioned:
- The C++ standard reserves all non-underscore-prefixed user-defined literal suffixes for the standard library. You’re not allowed to define your own literal suffixes that don’t start with an underscore (doing so is undefined behavior, per the standard).
- Any user-defined literal suffix you create for function calls must start with an underscore.
Now, consider what lives in std::literals: all the standard library’s literal operators use non-underscore suffixes—think "hello"s for std::string, 42ms for std::chrono::milliseconds, or 123i64 for std::int64_t.
Since you can’t legally use non-underscore suffixes for your own literals, there’s zero chance of naming collisions between your code and the contents of std::literals. Your custom literals will all use underscore-prefixed suffixes, which don’t overlap with anything in the standard library’s literal namespace.
This is a huge contrast to using namespace std, which dumps dozens of common identifiers (like vector, sort, string) into the global scope—setting you up for accidental conflicts with your own variable or function names. std::literals only introduces literal operators, which operate on a completely separate set of suffixes that you can’t legally use for your own code anyway.
A tiny caveat: if you intentionally flout the standard and define non-underscore suffixes, you will run into conflicts. But that’s a problem with non-compliant code, not with using std::literals.
While using it in local scopes (like inside a function) is still a slightly safer practice (as it limits the scope of the imported names), even global use here is low-risk and widely accepted in real-world C++ code.
内容的提问来源于stack exchange,提问作者ikh

