命名空间
变体
操作

std::basic_string 的推导指南

来自 cppreference.cn
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
定义于头文件 <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 满足 LegacyInputIteratorAlloc 满足 Allocator 时才参与重载决议。
2,3) 这些推导指南为 std::basic_string 提供,允许从 std::basic_string_view 进行推导。(3) 中的 size_type 参数类型指的是由推导指南推导出的类型的 size_type 成员类型。这些重载仅在 Alloc 满足 Allocator 时才参与重载决议。
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_stringstd::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()); // uses deduction guide (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); // uses deduction guide (4)
    assert(s4 == L"C++23");
#endif
}

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 3075 C++17 不支持从 basic_string_view 推导(LWG issue 2946 加剧了此问题) 添加了推导指南