Namespaces
Variants

std::reference_wrapper<T>:: get, std::reference_wrapper<T>:: operator T&

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
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* )
operator T & ( ) const noexcept ;
(1) (C++11以降)
(constexpr C++20以降)
T & get ( ) const noexcept ;
(2) (C++11以降)
(constexpr C++20以降)

格納された参照を返します。

目次

パラメータ

(なし)

戻り値

保存された参照。

#include <cassert>
#include <functional>
#include <map>
#include <optional>
#include <string_view>
using Map = std::map<std::string_view, int>;
using Opt = std::optional<std::reference_wrapper<Map::value_type>>;
Opt find(Map& m, std::string_view s)
{
    auto it = m.find(s);
    return it == m.end() ? Opt{} : Opt{*it};
}
int main()
{
    Map m{{"A", 1}, {"B", 2}, {"C", 3}};
    if (auto opt = find(m, "C"); opt)
        opt->get().second = 42;
        // std::optional::operator->() は std::reference_wrapper への参照を返し、その後
        // reference_wrapper::get() は map::value_type(std::pair)への参照を返す
    assert(m["C"] == 42);
}

関連項目

格納された関数を呼び出す
(公開メンバ関数)