How to correctly use std::reference_wrappers

无人久伴 提交于 2019-11-28 17:48:56

Class std::reference_wrapper<T> implements an implicit converting operator to T&:

operator T& () const noexcept;

and a more explicit getter:

T& get() const noexcept;

The implicit operator is called when a T (or T&) is required. For instance

void f(some_type x);
// ...
std::reference_wrapper<some_type> x;
some_type y = x; // the implicit operator is called
f(x);            // the implicit operator is called and the result goes to f.

However, sometimes a T is not necessarily expected and, in this case, you must use get. This happens, mostly, in automatic type deduction contexts. For instance,

template <typename U>
g(U x);
// ...
std::reference_wrapper<some_type> x;
auto y = x; // the type of y is std::reference_wrapper<some_type>
g(x);       // U = std::reference_wrapper<some_type>

To get some_type instead of std::reference_wrapper<some_type> above you should do

auto y = x.get(); // the type of y is some_type
g(x.get());       // U = some_type

Alternativelly the last line above could be replaced by g<some_type>(x);. However, for templatized operators (e.g. ostream::operator <<()) I believe you can't explicit the type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!