2

Recently I came across the following code in MSVC's standard library. What is the template <class _Ty> reference_wrapper(_Ty&) -> reference_wrapper<_Ty>; thing ? Is it a declaration of a copy constructor ? What should I google for ?

template <class _Ty>
class reference_wrapper
#if !_HAS_CXX20
    : public _Weak_types<_Ty>
#endif // !_HAS_CXX20
{
public:
    static_assert(is_object_v<_Ty> || is_function_v<_Ty>,
        "reference_wrapper<T> requires T to be an object type or a function type.");

    using type = _Ty;

    template <class _Uty, enable_if_t<conjunction_v<negation<is_same<_Remove_cvref_t<_Uty>, reference_wrapper>>,
                                          _Refwrap_has_ctor_from<_Ty, _Uty>>,
                              int> = 0>
    _CONSTEXPR20 reference_wrapper(_Uty&& _Val) noexcept(noexcept(_Refwrap_ctor_fun<_Ty>(_STD declval<_Uty>()))) {
        _Ty& _Ref = static_cast<_Uty&&>(_Val);
        _Ptr      = _STD addressof(_Ref);
    }

    _CONSTEXPR20 operator _Ty&() const noexcept {
        return *_Ptr;
    }

    _NODISCARD _CONSTEXPR20 _Ty& get() const noexcept {
        return *_Ptr;
    }

private:
    _Ty* _Ptr{};

public:
    template <class... _Types>
    _CONSTEXPR20 auto operator()(_Types&&... _Args) const
        noexcept(noexcept(_STD invoke(*_Ptr, static_cast<_Types&&>(_Args)...))) // strengthened
        -> decltype(_STD invoke(*_Ptr, static_cast<_Types&&>(_Args)...)) {
        return _STD invoke(*_Ptr, static_cast<_Types&&>(_Args)...);
    }
};

#if _HAS_CXX17
template <class _Ty>
reference_wrapper(_Ty&) -> reference_wrapper<_Ty>;
#endif // _HAS_CXX17
jcxz
  • 1,226
  • 2
  • 12
  • 25
  • 1
    user defined deduction guide... see subsection in: https://en.cppreference.com/w/cpp/language/class_template_argument_deduction – Klaus Aug 31 '22 at 11:11
  • It's a user defined template deduction guide – john Aug 31 '22 at 11:12
  • 1
    You should not "Google for" anything. You should get a C++ textbook that covers modern C++. You will find everything explained there. There's a popular myth that Google is a very good replacement for a C++ textbook. That myth is wrong. Many have attempted to learn C++ from Google search results. All of them have failed. – Sam Varshavchik Aug 31 '22 at 11:45
  • Interesting, thanks for pointing me to the answer. – jcxz Sep 02 '22 at 15:12

0 Answers0