How to correctly use std::reference_wrappers

前端 未结 1 1775
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 01:43

I am trying to understand std::reference_wrapper.

The following code shows that the reference wrapper does not behave exactly like a reference.

<
相关标签:
1条回答
  • 2020-12-13 02:38

    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.

    0 讨论(0)
提交回复
热议问题