std::basic_string 的推导指引

来自cppreference.com
< cpp‎ | string‎ | basic string


 
 
 
std::basic_string
 
在标头 <string> 定义
template<class InputIt,

          class Alloc =std::allocator<typenamestd::iterator_traits
                                                    <InputIt>::value_type>>
basic_string( InputIt, InputIt, Alloc = Alloc())
    -> basic_string<typenamestd::iterator_traits<InputIt>::value_type,
                    std::char_traits
                        <typenamestd::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/* 见下文 */::size_type,
              typename/* 见下文 */::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 推导。这些重载只有在 Alloc 满足分配器(Allocator) 时才会参与重载决议。
3)size_type 形参指代推导指引所推出类型的 size_type 嵌套类型。
4)std::basic_string 提供此推导指引,以允许从一个 std::from_range_t 标签和一个 input_range 推导。

注意:库确定类型是否满足老式输入迭代器(LegacyInputIterator) 的程度是未指定的,但最低要求是整数类型不具备输入迭代器的条件。类似地,确定类型是否满足分配器(Allocator) 是未指定的,但最低要求是成员类型 Alloc::value_type 必须存在,且表达式 std::declval<Alloc&>().allocate(std::size_t{}) 在作为不求值操作数时必须为良构。

目录

[编辑]注解

指引 (2,3) 是必要的,因为 std::basic_string 对于 std::basic_string_view 的构造函数被设为模板,以避免既存代码中的歧义,而这些模板不支持类模板实参推导。

[编辑]注解

功能特性测试标准功能特性
__cpp_lib_containers_ranges202202L(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 >= 202202Lstd::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 所恶化) 添加推导指引
close