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