std::literals::string_view_literals::operator""sv
来自 cppreference.com
< cpp | string | basic string view
定义在头文件 <string_view> 中 |
||
constexpr std::string_view operator ""sv( const char* str, std::size_t len ) noexcept; |
(1) | (自 C++17 起) |
constexpr std::u8string_view operator ""sv( const char8_t* str, std::size_t len ) noexcept; |
(2) | (自 C++20 起) |
constexpr std::u16string_view operator ""sv( const char16_t* str, std::size_t len ) noexcept; |
(3) | (自 C++17 起) |
constexpr std::u32string_view operator ""sv( const char32_t* str, std::size_t len ) noexcept; |
(4) | (自 C++17 起) |
constexpr std::wstring_view operator ""sv( const wchar_t* str, std::size_t len ) noexcept; |
(5) | (自 C++17 起) |
形成字符字面量的字符串视图。
1) 返回 std::string_view{str, len}.
2) 返回 std::u8string_view{str, len}.
3) 返回 std::u16string_view{str, len}.
4) 返回 std::u32string_view{str, len}.
5) 返回 std::wstring_view{str, len}.
内容 |
[编辑] 参数
str | - | 指向原始字符数组字面量开头的指针 |
len | - | 原始字符数组字面量的长度 |
[编辑] 返回值
该 std::basic_string_view 字面量。
[编辑] 注释
这些运算符在命名空间 std::literals::string_view_literals
中声明,其中 literals
和 string_view_literals
都是内联命名空间。可以使用以下任何一种方法访问这些运算符:
- using namespace std::literals,
- using namespace std::string_view_literals,或者
- using namespace std::literals::string_view_literals.
[编辑] 示例
运行此代码
#include <iostream> #include <string_view> #include <typeinfo> void print_each_character(const std::string_view sw) { for (char c : sw) std::cout << (c == '\0' ? '@' : c); std::cout << '\n'; } int main() { using namespace std::literals; std::string_view s1 = "abc\0\0def"; std::string_view s2 = "abc\0\0def"sv; std::cout << "s1.size(): " << s1.size() << "; s1: "; print_each_character(s1); std::cout << "s2.size(): " << s2.size() << "; s2: "; print_each_character(s2); std::cout << "substr(1, 4): " << "abcdef"sv.substr(1, 4) << '\n'; auto value_type_info = []<typename T>(T) { using V = typename T::value_type; std::cout << "sizeof " << typeid(V).name() << ": " << sizeof(V) << '\n'; }; value_type_info("char A"sv); value_type_info(L"wchar_t ∀"sv); value_type_info(u8"char8_t ∆"sv); value_type_info(u"char16_t ∇"sv); value_type_info(U"char32_t ∃"sv); value_type_info(LR"(raw ⊞)"sv); }
可能的输出
s1.size(): 3; s1: abc s2.size(): 8; s2: abc@@def substr(1, 4): bcde sizeof char: 1 sizeof wchar_t: 4 sizeof char8_t: 1 sizeof char16_t: 2 sizeof char32_t: 4 sizeof wchar_t: 4
[编辑] 另请参见
构造 basic_string_view (公有成员函数) | |
(C++14) |
将字符数组字面量转换为 basic_string (函数) |