名稱空間
變體
操作

std::basic_string 的推導指南

來自 cppreference.com
< 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 加劇了此問題) 添加了推導指南