C++14 中 std::string 的运算符后缀
operator suffix for std::string in c++14
我安装了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 std
和using 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;
}
相关文章:
- 增量运算符与后缀混淆
- 后缀 "&" (地址) 运算符 在 C++ 中
- 使用 C++ 将中缀转换为后缀(包括赋值运算符)
- C++编译器如何扩展前缀和后缀运算符++()?
- 指向重载前缀和后缀运算符中的类对象的指针
- 输入迭代器 - 星号和后缀运算符
- C++如何知道在重载运算符时增量++是前缀或后缀
- 后缀运算符链表泛型节点迭代器
- 如何使用虚拟后缀运算符解决切片问题
- 前缀和后缀运算符 C++
- C++14 中 std::string 的运算符后缀
- 后缀运算符不应该被视为二元运算符吗
- 编译器如何翻译后缀/前缀运算符
- 虚拟参数在后缀运算符重载中的用途?C++
- 涡轮增压C++(非可视)(后缀和前缀运算符)
- while 循环中的后缀运算符
- 如何计算前缀和后缀运算符的组合
- C++ “运算符=”(后缀到中缀)不匹配
- C++ 重载'--'后缀运算符
- 未声明运算符++后缀