在不使用命名空间std的情况下使用字符串文字 [英] Using string literals without using namespace std

查看:114
本文介绍了在不使用命名空间std的情况下使用字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++社区中建议不要使用使用命名空间std; 。但是假设您要使用字符串文字,例如 auto s = dummy s;
不使用使用命名空间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?

推荐答案

operator s 位于命名空间 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
            //...
        }
    }
}

因此,仅获取字符串文字,请使用使用命名空间std :: string_literals;

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

或者,如果您想包含每个文字-包括字符串文字(例如 s 秒,如果您包括 chrono ,...):使用命名空间std :: 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)

这篇关于在不使用命名空间std的情况下使用字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆