Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `using namespace std::literals` safe?

Generally, using namespace in global scope is considered as a bad practice. However, according to cppreference, the identifiers not starting with underscore(_) are reserved for standard library in the case of user-defined literals.

the identifier to use as the ud-suffix for the user-defined literals that will call this function. Must begin with the underscore _: the suffixes that do not begin with the underscore are reserved for the literal operators provided by the standard library.

Does that mean I can safely do using namespace std::literals; in global scope?

like image 713
ikh Avatar asked Mar 27 '18 01:03

ikh


People also ask

Is it OK to use using namespace std?

The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.

Why namespace std is not recommended?

It is considered "bad" only when used globally. Because: You clutter the namespace you are programming in. Readers will have difficulty seeing where a particular identifier comes from, when you use many using namespace xyz; .

Why we should not use using namespace std in C++?

Bad Practice: using namespace std So if we are using that other namespace (with the other cout entity) along with the std namespace, then the compiler will not know which cout to use. As a result, we'll get an error whenever we use cout .

Should you use namespace CPP?

A namespace defines a new scope. They provide a way to avoid name collisions. Namespaces in C++ are most often used to avoid naming collisions. Although namespaces are used extensively in recent C++ code, most older code does not use this facility.


1 Answers

These user-defined literals are pretty new. You have to understand the Standards body here; they didn't have experience with actual use (unlike say Boost). So they came up with a conservative approach: on one side, the predefined suffixes are in namespace std, on the other side the user-defined literals must start with _.

This indeed leaves an open space in the middle: suffixes that do not start with _ but are defined in the global namespace. As we gain experience with the existing literals, a decision might be made who gets to define such literals.

So, to future-proof your code, you shouldn't cause too much problems for others regardless of what choice is made here in future standards. But does that mean "avoid the using in the global namespace"? No. Each Translation unit gets to make its own choice. In your own .cpp files, do what you like. But you shouldn't affect other Translation units. Therefore the actual rule is:

using namespace std::literals is not safe in headers.

like image 144
MSalters Avatar answered Nov 10 '22 00:11

MSalters