Using string literals without using namespace std

operator""s is in 2 inlined namespaces in namespace std. It basically looks like this:

namespace std
{
    inline namespace literals
    {
        inline namespace string_literals
        {
            //operator""s implementation
            //...
        }
    }
}

So, to only get the string literals, use using namespace std::string_literals;.

Alternatevely, if you want to include every literal - including the string literals (like s for seconds if you include chrono, ...): using namespace std::literals;.

Depending on the situation, you might also consider using:

using std::string_literals::operator""s;

instead of importing every name from that namespace.

Note that you should still not include it in a header, at global level (but you can do it inside inline or member functions or namespaces you control)


For string literals you can use:

using namespace std::string_literals;

That will pull about 4 names into the namespace which is fine. But when you do:

using namespace std;

Then you pull in thousands of names, many of which are commonly used in programs like count and time. This can create hard to find bugs from accidentally referring to the wrong thing.

That's not an issue with the string literals.

Also none of the names that using namespace std::string_literals; brings in should interfere with user defined names because user defined string literals must begin with _ (according to the standard) which avoids conflicts.

However you should still avoid using namespace std::string_literals; in the global namespace of a header file because you should not impose any feature on a user that they don't request.


Above operators are declared in the namespace std::literals::string_literals, where both literals and string_literals are inline namespaces. Access to these operators can be gained with using namespace std::literals, using namespace std::string_literals, and using namespace std::literals::string_literals

Source : std::literals::string_literals::operator""s

Tags:

C++

C++11