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 起)
(自 C++20 起为 constexpr)
T & get ( ) const noexcept ;
(2) (自 C++11 起)
(自 C++20 起为 constexpr)

返回存储的引用。

目录

参数

(无)

返回值

存储的引用。

示例

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

参见

调用存储的函数
(公开成员函数)