• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    class template
    <functional>

    std::reference_wrapper

    namespace std {
      template <class T>
      class reference_wrapper;
    }
    

    概要

    reference_wrapperは、コピー・代入可能なオブジェクトとして持ちまわれる参照オブジェクトを提供する。コピー不可なクラス (例:std::istream) をポインタで保持する代わりにreference_wrapperで保持することができる。また、reference_wrapperクラスは、関数テンプレートに変数を参照として渡すためにも使用できる。

    C++17からは、このクラスはトリビアルコピー可能であると規定された。 また、C++20からは、テンプレートパラメーターT不完全型をサポートしている。

    メンバ関数

    名前 説明 対応バージョン
    (constructor) コンストラクタ C++11
    ~reference_wrapper() = default; デストラクタ C++11
    operator= 代入演算子 C++11
    get 生参照の取得 C++11
    operator T&() 生参照への変換 C++11
    operator() 関数オブジェクト呼び出し C++11

    メンバ型

    名前 説明 対応バージョン
    type 参照される型 (テンプレートパラメータ T) C++11
    result_type Tを関数・関数オブジェクトとして扱った時の戻り値 C++11
    C++17から非推奨
    C++20で削除
    argument_type Tを一引数の関数・関数オブジェクトとして扱った時の引数型 C++11
    C++17から非推奨
    C++20で削除
    first_argument_type Tを二引数の関数・関数オブジェクトとして扱った時の第一引数型 C++11
    C++17から非推奨
    C++20で削除
    second_argument_type Tを二引数の関数・関数オブジェクトとして扱った時の第二引数型 C++11
    C++17から非推奨
    C++20で削除

    非メンバ関数

    ヘルパ関数

    名前 説明 対応バージョン
    ref T&に対応するreference_wrapperオブジェクトの生成 C++11
    cref const T&に対応するreference_wrapperオブジェクトの生成 C++11

    比較演算子

    名前 説明 対応バージョン
    operator== 等値比較 C++26
    operator!= 非等値比較 (==により使用可能) C++26
    operator<=> 三方比較 C++26
    operator< 左辺が右辺より小さいかを判定する (<=>により使用可能) C++26
    operator<= 左辺が右辺以下を判定する (<=>により使用可能) C++26
    operator> 左辺が右辺より大きいかを判定する (<=>により使用可能) C++26
    operator>= 左辺が右辺以上かを判定する (<=>により使用可能) C++26

    推論補助

    名前 説明 対応バージョン
    (deduction_guide) クラステンプレートの推論補助 C++17

    #include <iostream>
    #include <functional>
    
    void f(int& x)
    {
      ++x;
    }
    
    template <class T>
    void g(T x)
    {
      f(x);
    }
    
    int main()
    {
      int x = 3;
    
      // 関数テンプレートの型推論によって、xの型が非参照のintと見なされる
    //g(x);
    
      // 関数テンプレートに変数を参照として渡す
      g(std::ref(x));
    
      std::cout << x << std::endl;
    }
    

    出力

    4
    

    不完全型を保持する例

    #include <functional>
    #include <iostream>
    
    struct my_struct;
    my_struct& get_my_struct();
    
    int main()
    {
      [[maybe_unused]]
      std::reference_wrapper<my_struct> s = get_my_struct(); // 不完全型 my_struct の使用
    }
    
    struct my_struct
    {
      void hello() { std::cout << "Hello, world!"; }
    };
    
    my_struct& get_my_struct()
    {
      static my_struct obj = my_struct{};
      return obj;
    }
    

    出力

    0
    

    バージョン

    言語

    • C++11

    処理系

    参照