Namespaces
Variants

std:: reference_wrapper

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Reference wrappers
reference_wrapper
(C++11)
(C++11) (C++11)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
ヘッダーで定義 <functional>
template < class T >
class reference_wrapper ;
(C++11以降)

std::reference_wrapper は、参照をコピー可能で代入可能なオブジェクトにラップするクラステンプレートです。

具体的には、 std::reference_wrapper は、 CopyConstructible かつ CopyAssignable なラッパーであり、型 T のオブジェクトへの参照または関数への参照を包みます。 std::reference_wrapper のインスタンスはオブジェクトであり(コピーやコンテナへの格納が可能)、暗黙的に T & に変換可能です。そのため、基になる型を参照で受け取る関数の引数として使用することができます。

格納された参照が Callable である場合、 std::reference_wrapper は同じ引数で呼び出し可能です。

ヘルパー関数 std::ref および std::cref は、しばしば std::reference_wrapper オブジェクトを生成するために使用されます。

std::reference_wrapper は、オブジェクトを参照で std::bind std::thread のコンストラクタ、あるいはヘルパー関数である std::make_pair std::make_tuple に渡すために使用されます。また、通常は参照を保持できない標準コンテナ( std::vector など)内部で参照を格納する仕組みとしても使用できます。

std::reference_wrapper TriviallyCopyable であることが保証されています。

(C++17以降)

T は不完全型であってもよい。

(C++20以降)

目次

メンバー型

定義
type T
result_type
(C++17で非推奨)
(C++20で削除)
T が関数の場合の戻り値の型。それ以外の場合、定義されない。
argument_type
(C++17で非推奨)
(C++20で削除)
  • T が型 A1 の引数を1つ取る関数または関数ポインタの場合、 argument_type A1
  • T がクラス T0 の引数を取らないメンバ関数ポインタの場合、 argument_type T0 * (CV修飾される可能性あり)
  • T がメンバ型 T :: argument_type を持つクラス型の場合、 argument_type はそのエイリアス
first_argument_type
(C++17で非推奨)
(C++20で削除)
  • T が型 A1 A2 の引数を2つ取る関数または関数ポインタの場合、 first_argument_type A1
  • T がクラス T0 の引数を1つ取るメンバ関数ポインタの場合、 first_argument_type T0 * (CV修飾される可能性あり)
  • T がメンバ型 T :: first_argument_type を持つクラス型の場合、 first_argument_type はそのエイリアス
second_argument_type
(C++17で非推奨)
(C++20で削除)
  • T が型 A1 A2 の引数を2つ取る関数または関数ポインタの場合、 second_argument_type A2
  • T がクラス T0 の引数 A1 を1つ取るメンバ関数ポインタの場合、 second_argument_type A1 (CV修飾される可能性あり)
  • T がメンバ型 T :: second_argument_type を持つクラス型の場合、 second_argument_type はそのエイリアス

メンバー関数

新しい std::reference_wrapper オブジェクトに参照を格納する
(public member function)
std::reference_wrapper を再バインドする
(public member function)
格納された参照にアクセスする
(public member function)
格納された関数を呼び出す
(public member function)

非メンバー関数

reference_wrapper オブジェクトを格納された参照として比較する
(関数)

推論ガイド (C++17以降)

ヘルパークラス

reference_wrapper と非 reference_wrapper の共通参照型を決定する
(クラステンプレートの特殊化)

実装例

namespace detail
{
    template<class T> constexpr T& FUN(T& t) noexcept { return t; }
    template<class T> void FUN(T&&) = delete;
}
template<class T>
class reference_wrapper
{
public:
    // 型
    using type = T;
    // 構築/コピー/破棄
    template<class U, class = decltype(
        detail::FUN<T>(std::declval<U>()),
        std::enable_if_t<!std::is_same_v<reference_wrapper, std::remove_cvref_t<U>>>()
    )>
    constexpr reference_wrapper(U&& u)
        noexcept(noexcept(detail::FUN<T>(std::forward<U>(u))))
        : _ptr(std::addressof(detail::FUN<T>(std::forward<U>(u)))) {}
    reference_wrapper(const reference_wrapper&) noexcept = default;
    // 代入
    reference_wrapper& operator=(const reference_wrapper& x) noexcept = default;
    // アクセス
    constexpr operator T& () const noexcept { return *_ptr; }
    constexpr T& get() const noexcept { return *_ptr; }
    template<class... ArgTypes>
    constexpr std::invoke_result_t<T&, ArgTypes...>
        operator() (ArgTypes&&... args ) const
            noexcept(std::is_nothrow_invocable_v<T&, ArgTypes...>)
    {
        return std::invoke(get(), std::forward<ArgTypes>(args)...);
    }
private:
    T* _ptr;
};
// 推論ガイド
template<class T>
reference_wrapper(T&) -> reference_wrapper<T>;

std::reference_wrapper を参照のコンテナとして使用する方法を示します。これにより、複数のインデックスを使用して同じコンテナにアクセスすることが可能になります。

#include <algorithm>
#include <functional>
#include <iostream>
#include <list>
#include <numeric>
#include <random>
#include <vector>
void println(auto const rem, std::ranges::range auto const& v)
{
    for (std::cout << rem; auto const& e : v)
        std::cout << e << ' ';
    std::cout << '\n';
}
int main()
{
    std::list<int> l(10);
    std::iota(l.begin(), l.end(), -4);
    // can't use shuffle on a list (requires random access), but can use it on a vector
    std::vector<std::reference_wrapper<int>> v(l.begin(), l.end());
    std::ranges::shuffle(v, std::mt19937{std::random_device{}()});
    println("Contents of the list: ", l);
    println("Contents of the list, as seen through a shuffled vector: ", v);
    std::cout << "Doubling the values in the initial list...\n";
    std::ranges::for_each(l, [](int& i) { i *= 2; });
    println("Contents of the list, as seen through a shuffled vector: ", v);
}

出力例:

Contents of the list: -4 -3 -2 -1 0 1 2 3 4 5
Contents of the list, as seen through a shuffled vector: -1 2 -2 1 5 0 3 -3 -4 4
Doubling the values in the initial list...
Contents of the list, as seen through a shuffled vector: -2 4 -4 2 10 0 6 -6 -8 8

関連項目

(C++11) (C++11)
引数から型が推論される std::reference_wrapper を作成する
(関数テンプレート)
(C++11)
関数オブジェクトに1つ以上の引数をバインドする
(関数テンプレート)
std::reference_wrapper でラップされた参照型を取得する
(クラステンプレート)