Namespaces
Variants

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

来自 zh.cppreference.net
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
透明运算符包装器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧式绑定器和适配器
(至 C++17*)
(至 C++17*)
(至 C++17*)
(至 C++17*)
(至 C++17*)(至 C++17*)(至 C++17*)(至 C++17*)
(至 C++20*)
(至 C++20*)
(至 C++17*)(至 C++17*)
(至 C++17*)(至 C++17*)

(至 C++17*)
(至 C++17*)(至 C++17*)(至 C++17*)(至 C++17*)
(至 C++20*)
(至 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);
}

参见

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