std::basic_string 的推导指引 std::basic_string
源自 zh.cppreference.net
| 定义于头文件 <string>
|
||
template< class InputIt, class Alloc = std::allocator<
typename std::iterator_traits<InputIt>::value_type> >
basic_string( InputIt, InputIt, Alloc = Alloc() )
-> basic_string<typename std::iterator_traits<InputIt>::value_type,
std::char_traits<
typename std::iterator_traits<InputIt>::value_type>, Alloc>;
|
(1) | (C++17 起) |
template< class CharT,
class Traits,
class Alloc = std::allocator<CharT> >
explicit basic_string( std::basic_string_view<CharT, Traits>, const Alloc& = Alloc() )
-> basic_string<CharT, Traits, Alloc>;
|
(2) | (C++17 起) |
template< class CharT,
class Traits,
class Alloc = std::allocator<CharT>> >
basic_string( std::basic_string_view<CharT, Traits>,
typename /* see below */::size_type,
typename /* see below */::size_type,
const Alloc& = Alloc() )
-> basic_string<CharT, Traits, Alloc>;
|
(3) | (C++17 起) |
template< ranges::input_range R,
class Alloc = std::allocator<ranges::range_value_t<R>> >
basic_string( std::from_range_t, R&&, Alloc = Alloc() )
-> basic_string<ranges::range_value_t<R>,
std::char_traits<ranges::range_value_t<R>>, Alloc>;
|
(4) | (C++23 起) |
1) 为 std::basic_string 提供此推导指引,以允许从迭代器范围进行推导。仅当
InputIt 满足 LegacyInputIterator 且 Alloc 满足 Allocator 时,此重载才会参与重载决议。2,3) 为 std::basic_string 提供这些推导指引,以允许从 std::basic_string_view 进行推导。
size_type 在 (3) 中的参数类型指的是由推导指引推导出的类型的 size_type 成员类型。仅当 Alloc 满足 Allocator 时,这些重载才会参与重载决议。注意:库确定类型不满足 LegacyInputIterator 的程度是未指定的,但至少整数类型不具备输入迭代器资格。同样地,它确定类型不满足 Allocator 的程度也是未指定的,但至少成员类型 Alloc::value_type 必须存在,且表达式 std::declval<Alloc&>().allocate(std::size_t{}) 在作为未求值操作数时必须是良构的。
注释
需要推导指引 ( 2,3 ) 是因为 std::basic_string 针对 std::basic_string_view 的构造函数被实现为模板,以避免在现有代码中引发歧义,而这些模板不支持类模板实参推导。
注释
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_containers_ranges
|
202202L
|
(C++23) | 范围感知 的构造与插入;重载 ( 4 ) |
示例
运行此代码
#include <cassert> #include <string> #include <vector> int main() { std::vector<char> v = {'a', 'b', 'c'}; std::basic_string s1(v.begin(), v.end()); // 使用推导指南 (1) assert(s1 == "abc"); #if __cpp_lib_containers_ranges >= 202202L std::vector<wchar_t> v4{0x43, 43, 053, 0x32, 0x33}; std::basic_string s4(std::from_range, v4); // 使用推导指南 (4) assert(s4 == L"C++23"); #endif }
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用范围 | 发布时行为 | 正确行为 |
|---|---|---|---|
| LWG 3075 | C++17 |
不支持从
basic_string_view
进行推导
(因 LWG 问题 2946 加剧) |
已添加推导指南 |