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

Khu*_*hid 22 c++ c++11 c++14

我安装了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; 
}
Run Code Online (Sandbox Code Playgroud)

如果我评论1和2,我得到编译错误.但我知道在大项目中1.方法很糟糕,2.方法很陌生.

QA:我是否可以使用运营商"" S没有任何文字using namespace stdusing std::operator ""s

Dan*_*rey 25

结束评论:

你必须明确地引入这些运算符using.这是标准的意图.你应该考虑只提供你需要的东西

using namespace std::literals;
Run Code Online (Sandbox Code Playgroud)

要么

using namespace std::literals::string_literals;
Run Code Online (Sandbox Code Playgroud)

根据您的需要,后者在有疑问的情况下更可取(仅拉动您需要的东西,而不是更多).与所有使用声明或指令一样,您希望将它们限制在实际的最小范围内.

需要明确提取运算符的原因是后缀可能会在未来的扩展中在不同的上下文中重用.