E. Vakili E. Vakili - 3 months ago 13
C++ Question

Using string literals without using namespace std

There's recommendation in C++ community to not to use

using namespace std;
. But suppose you want to use string literals e.g.
auto s = "dummy's;
.
Not using
using namespace std;
cause to failed compile. What is the solution?

Answer

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)