名前空間
変種
操作

std::basic_string の推論ガイド

From 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のために提供されています。このオーバーロードは、InputItLegacyInputIteratorを満たし、AllocAllocatorを満たす場合にのみ、オーバーロード解決に参加します。
2,3) これらの推論ガイドは、std::basic_stringstd::basic_string_viewから推論できるようにするために提供されています。(3)size_typeパラメータ型は、推論ガイドによって推論される型のsize_typeメンバ型を参照します。これらのオーバーロードは、AllocAllocatorを満たす場合にのみ、オーバーロード解決に参加します。
4) この推論ガイドは、std::basic_stringstd::from_range_tタグとinput_rangeからの推論を可能にするために提供されています。

注意: ライブラリが型がLegacyInputIteratorを満たさないと判断する範囲は未指定ですが、最低限、整数型は入力イテレータとして適格ではありません。同様に、型がAllocatorを満たさないと判断する範囲も未指定ですが、最低限、メンバ型Alloc::value_typeが存在し、評価されないオペランドとして扱われる場合、式std::declval<Alloc&>().allocate(std::size_t{})がwell-formedである必要があります。

目次

[編集] Notes

ガイド(2,3)は、std::basic_stringstd::basic_string_view用のコンストラクタが、既存のコードでの曖昧さを避けるためにテンプレート化されており、それらのテンプレートがクラステンプレート引数推論をサポートしていないため必要です。

[編集] Notes

機能テストマクロ 規格 機能
__cpp_lib_containers_ranges 202202L (C++23) Ranges対応の構築と挿入。オーバーロード(4)

[編集] Example

#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
}

[編集] Defect reports

以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。

DR 適用対象 公開された動作 正しい動作
LWG 3075 C++17 basic_string_viewからの推論はサポートされていませんでした(LWG issue 2946により悪化)。 推論ガイドが追加されました
English 日本語 中文(简体) 中文(繁體)