简体   繁体   English

c ++ 14中std :: string的运算符后缀

[英]operator suffix for std::string in c++14

I install Clang 3.4, and test suffix operator for string literal ""s. 我安装了Clang 3.4,并为字符串文字“”s测试后缀运算符。

#include <string>

//1. using namespace std; // without compile error.
//2. using std::operator ""s; // or without it compile error, too.
// for success compiles, need 1. or 2. line.

int main()
{
    auto s = "hello world"s; 
}

If I comment 1 and 2 , I get compile error. 如果我评论1和2,我得到编译错误。 But I know in big projects 1.-method is bad, and 2.-method is stranger. 但我知道在大项目中1.方法很糟糕,2.方法很陌生。

QA: Can I use operator ""s without any writing using namespace std and using std::operator ""s ? 问:我可以使用运算符“”而无需using namespace stdusing std::operator ""s进行任何编写吗?

Wrapping up the comments: 结束评论:

You have to explicitly pull in those operators with using . 你必须明确地using这些运算符。 This is what is intended by the standard. 这是标准的意图。 You should consider to pull in only what you need, either 你应该考虑只提供你需要的东西

using namespace std::literals;

or 要么

using namespace std::literals::string_literals;

depending on your needs, the latter being preferable in case of doubt (only pull in what you need, not more). 根据您的需要,后者在有疑问的情况下更可取(仅拉动您需要的东西,而不是更多)。 As with all using declarations or directives, you want to limit them to the smallest scope that is practical. 与所有使用声明或指令一样,您希望将它们限制在实际的最小范围内。

The reason behind the need to pull the operators in explicitly is that the suffixes might be re-used in future extensions in different contexts. 需要明确提取运算符的原因是后缀可能会在未来的扩展中在不同的上下文中重用。

If you found 2nd option strange, that is actually pretty common, you could limit the scope of the "using namespace std" like this: 如果您发现第二个选项很奇怪,这实际上很常见,您可以限制“using namespace std”的范围,如下所示:

int main()
{
    using namespace std;
    auto s = "hello world"s; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM