std::reference_wrapper<T>::get, std::reference_wrapper<T>::operator T&
来自 zh.cppreference.net
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); }
参见
|
调用存储的函数
(公开成员函数) |