std::basic_string_view
的推导指南
来自 cppreference.com
< cpp | string | basic string view
定义在头文件 <string_view> 中 |
||
template< class It, class End > basic_string_view( It, End ) -> basic_string_view<std::iter_value_t<It>>; |
(1) | (自 C++20 起) |
template< class R > basic_string_view( R&& ) -> basic_string_view<ranges::range_value_t<R>>; |
(2) | (自 C++23 起) |
这些 推导指南 是为 std::basic_string_view 提供的。
1) 此推导指南允许从迭代器-哨兵对推断字符类型。仅当
It
满足 contiguous_iterator
且 End
满足 sized_sentinel_for
针对 It
时,此重载才参与重载解析。[编辑] 示例
运行此代码
#include <array> #include <iostream> #include <string_view> int main() { std::array a1{'n', 'u', 'c', 'l', 'e', 'o', 'n', 's', ':', '\n'}; std::basic_string_view s1(a1.cbegin(), a1.cend()); // deduction: CharT -> char static_assert(std::is_same_v<decltype(s1)::value_type, char>); std::cout << s1; std::array a2{L'p', L'r', L'o', L't', L'o', L'n', L's', L'\n'}; std::basic_string_view s2(a2.cbegin(), a2.cend()); // deduction: CharT -> wchar_t static_assert(std::is_same_v<decltype(s2)::value_type, wchar_t>); std::wcout << s2; std::array<long, 9> a3{'n', 'e', 'u', 't', 'r', 'o', 'n', 's', '\n'}; std::basic_string_view s3(a3.cbegin(), a3.cend()); // deduction: CharT -> long static_assert(std::is_same_v<decltype(s3)::value_type, long>); for (const auto e : s3) std::cout << static_cast<char>(e); }
输出
nucleons: protons neutrons