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

operator suffix for std::string in c++14

本文关键字:运算符 后缀 string std C++14      更新时间:2023-10-16

我安装了Clang 3.4,并测试字符串文字"的后缀运算符。

#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; 
}

如果我评论 1 和 2 ,我得到编译错误。但我知道在大项目中 1.-方法不好,2.方法更奇怪。

QA:我可以在没有任何写入using namespace stdusing std::operator ""s的情况下使用运算符"吗?

总结评论:

您必须使用 using 显式拉入这些运算符。这就是标准的意图。您应该考虑只拉入您需要的内容,或者

using namespace std::literals;

using namespace std::literals::string_literals;

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

需要显式拉入运算符的原因是,后缀可能会在不同的上下文中在未来的扩展中重复使用。

如果你觉得第二个选项很奇怪,这实际上很常见,你可以像这样限制"使用命名空间 std"的范围:

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