c/c++语言开发共享引用传参与reference_wrapper

本文是“系列的第3篇。 引用传参 我有一个函数: 因为参数类型是 ,所以函数能够修改传入的整数,而非其拷贝。 然后我用 把它和一个 绑定起来: int i = 1; auto f = std::bind(modify, i); f(); std::cout `对象。 reference_wrapp …

c/c++开发分享引用传参与reference_wrapper是的第3篇。

引用传参

我有一个函数:

void modify(int& i) {     ++i; } 

因为参数类型是int&,所以函数能够修改传入的整数,而非其拷贝。

然后我用把它和一个int绑定起来:

int i = 1; auto f = std::bind(modify, i); f(); std::cout << i << std::endl; 

可是i还是1,为什么呢?原来std::bind会把所有参数都拷贝,即使它是个左值引用。所以modify中修改的变量,实际上是std::bind返回的函数对象中的一个int,并非原来的i

我们需要std::reference_wrapper

int j = 1; auto g = std::bind(modify, std::ref(j)); g(); std::cout << j << std::endl; 

std::ref(j)返回的就是std::reference_wrapper<int>对象。

reference_wrapper

std::reference_wrapper及其辅助函数大致长成这样:

template<typename t> class reference_wrapper { public:     template<typename u>     reference_wrapper(u&& x) : ptr(std::addressof(x)) { }          reference_wrapper(const reference_wrapper&) noexcept = default;     reference_wrapper& operator=(const reference_wrapper& x) noexcept = default;       constexpr operator t& () const noexcept { return *ptr; }     constexpr t& get() const noexcept { return *ptr; }       template<typename... args>     auto operator()(args&&... args) const     {         return get()(std::forward<args>(args)...);     }      private:     t* ptr; };  template<typename t> reference_wrapper<t> ref(t& t) noexcept {     return reference_wrapper<t>(t); } template<typename t> reference_wrapper<t> ref(reference_wrapper<t> t) noexcept {     return t; } template<typename t> void ref(const t&&) = delete;  template<typename t> reference_wrapper<const t> cref(const t& t) noexcept {     return reference_wrapper<const t>(t); } template<typename t> reference_wrapper<const t> cref(reference_wrapper<t> t) noexcept {     return reference_wrapper<const t>(t.get()); } template<typename t> void cref(const t&&) = delete; 

可见,std::reference_wrapper不过是包装一个指针罢了。它重载了operator t&,对象可以隐式转换回原来的引用;它还重载了operator(),包装函数对象时可以直接使用函数调用运算符;调用其他成员函数时,要先用get方法获得其内部的引用。

std::reference_wrapper的意义在于:

  1. 引用不是对象,不存在引用的引用、引用的数组等,但std::reference_wrapper是,使得定义引用的容器成为可能;

  2. 模板函数无法辨别你在传入左值引用时的意图是传值还是传引用,std::refstd::cref告诉那个模板,你要传的是引用。

实现

尽管std::reference_wrapper的简单(但是不完整的)实现可以在50行以内完成,gcc的标准库为了实现一个完美的std::reference_wrapper还是花了300多行(还不包括std::invoke),其中200多行是为了定义result_typeargument_typefirst_argument_typesecond_argument_type这几个在c++17中废弃、c++20中移除的成员类型。如果你是在c++20完全普及以后读到这篇文章的,就当考古来看吧!

继承成员类型

定义这些类型所用的工具是继承,一种特殊的、没有“is-a”含义的public继承。以_maybe_unary_or_binary_function为例:

template<typename _arg, typename _result>   struct unary_function   {     typedef _arg      argument_type;        typedef _result   result_type;     };  template<typename _arg1, typename _arg2, typename _result>   struct binary_function   {     typedef _arg1     first_argument_type;      typedef _arg2     second_argument_type;     typedef _result   result_type;   };  template<typename _res, typename... _argtypes>   struct _maybe_unary_or_binary_function { };  template<typename _res, typename _t1>   struct _maybe_unary_or_binary_function<_res, _t1>   : std::unary_function<_t1, _res> { };  template<typename _res, typename _t1, typename _t2>   struct _maybe_unary_or_binary_function<_res, _t1, _t2>   : std::binary_function<_t1, _t2, _res> { }; 

然后std::function<res(args...)>去继承_maybe_unary_or_binary_function<res, args...>:当sizeof...(args) == 1时继承到std::unary_function,定义argument_type;当sizeof...(args) == 2时继承到std::binary_function,定义first_argument_typesecond_argument_type;否则继承一个空的_maybe_unary_or_binary_function,什么定义都没有。

各种模板技巧,tag dispatching、sfinae等,面对这种需求都束手无策,只有继承管用。

成员函数特征

template<typename _signature>   struct _mem_fn_traits;  template<typename _res, typename _class, typename... _argtypes>   struct _mem_fn_traits_base   {     using __result_type = _res;     using __maybe_type       = _maybe_unary_or_binary_function<_res, _class*, _argtypes...>;     using __arity = integral_constant<size_t, sizeof...(_argtypes)>;   };  #define _glibcxx_mem_fn_traits2(_cv, _ref, _lval, _rval)                   template<typename _res, typename _class, typename... _argtypes>            struct _mem_fn_traits<_res (_class::*)(_argtypes...) _cv _ref>           : _mem_fn_traits_base<_res, _cv _class, _argtypes...>                    {                                                                          using __vararg = false_type;                                           };                                                                     template<typename _res, typename _class, typename... _argtypes>            struct _mem_fn_traits<_res (_class::*)(_argtypes... ...) _cv _ref>       : _mem_fn_traits_base<_res, _cv _class, _argtypes...>                    {                                                                          using __vararg = true_type;                                            };  #define _glibcxx_mem_fn_traits(_ref, _lval, _rval)                 _glibcxx_mem_fn_traits2(              , _ref, _lval, _rval)      _glibcxx_mem_fn_traits2(const         , _ref, _lval, _rval)      _glibcxx_mem_fn_traits2(volatile      , _ref, _lval, _rval)      _glibcxx_mem_fn_traits2(const volatile, _ref, _lval, _rval)  _glibcxx_mem_fn_traits( , true_type, true_type) _glibcxx_mem_fn_traits(&, true_type, false_type) _glibcxx_mem_fn_traits(&&, false_type, true_type)  #if __cplusplus > 201402l _glibcxx_mem_fn_traits(noexcept, true_type, true_type) _glibcxx_mem_fn_traits(& noexcept, true_type, false_type) _glibcxx_mem_fn_traits(&& noexcept, false_type, true_type) #endif  #undef _glibcxx_mem_fn_traits #undef _glibcxx_mem_fn_traits2 

_mem_fn_traits是成员函数类型的特征(trait)类型,定义了__result_type__maybe_type__arity__vararg成员类型:__arity表示元数,__vararg指示成员函数类型是否是可变参数的(如std::printf,非变参模板)。... ...中的前三个点表示变参模板,后三个点表示可变参数,参考:what are the 6 dots in template parameter packs?

成员函数类型有constvolatile&/&&noexcept(c++17开始noexcept成为函数类型的一部分)4个维度,共24种,单独定义太麻烦,所以用了宏。

检测成员类型

一个类模板,当模板参数的类型定义了成员类型result_type时该类模板也定义它,否则不定义它,如何实现?我刚刚新学到一种方法,用void_t(即__void_t)。

void_t的定义出奇地简单:

template<typename...> using void_t = void; 

不就是一个void嘛,有什么用呢?请看:

template<typename _functor, typename = __void_t<>>   struct _maybe_get_result_type   { };  template<typename _functor>   struct _maybe_get_result_type<_functor,                                 __void_t<typename _functor::result_type>>   { typedef typename _functor::result_type result_type; }; 

第二个定义是第一个定义的特化。当_functor类型定义了result_type时,两个都正确,但是第二个更加特化,匹配到第二个,传播result_type;反之,第二个在实例化过程中发生错误,根据sfinae,匹配到第一个,不定义result_type

void_t的技巧,本质上还是sfinae。

以下两个类同理:

template<typename _tp, typename = __void_t<>>   struct _refwrap_base_arg1   { };  template<typename _tp>   struct _refwrap_base_arg1<_tp,                             __void_t<typename _tp::argument_type>>   {     typedef typename _tp::argument_type argument_type;   };  template<typename _tp, typename = __void_t<>>   struct _refwrap_base_arg2   { };  template<typename _tp>   struct _refwrap_base_arg2<_tp,                             __void_t<typename _tp::first_argument_type,                                      typename _tp::second_argument_type>>   {     typedef typename _tp::first_argument_type first_argument_type;     typedef typename _tp::second_argument_type second_argument_type;   }; 

分类讨论

#if __cpp_noexcept_function_type #define _glibcxx_noexcept_parm , bool _ne #define _glibcxx_noexcept_qual noexcept (_ne) #else #define _glibcxx_noexcept_parm #define _glibcxx_noexcept_qual #endif  /**  *  base class for any function object that has a weak result type, as  *  defined in 20.8.2 [func.require] of c++11. */ template<typename _functor>   struct _weak_result_type_impl   : _maybe_get_result_type<_functor>   { };  /// retrieve the result type for a function type. template<typename _res, typename... _argtypes _glibcxx_noexcept_parm>   struct _weak_result_type_impl<_res(_argtypes...) _glibcxx_noexcept_qual>   { typedef _res result_type; };  /// retrieve the result type for a varargs function type. template<typename _res, typename... _argtypes _glibcxx_noexcept_parm>   struct _weak_result_type_impl<_res(_argtypes......) _glibcxx_noexcept_qual>   { typedef _res result_type; };  /// retrieve the result type for a function pointer. template<typename _res, typename... _argtypes _glibcxx_noexcept_parm>   struct _weak_result_type_impl<_res(*)(_argtypes...) _glibcxx_noexcept_qual>   { typedef _res result_type; };  /// retrieve the result type for a varargs function pointer. template<typename _res, typename... _argtypes _glibcxx_noexcept_parm>   struct   _weak_result_type_impl<_res(*)(_argtypes......) _glibcxx_noexcept_qual>   { typedef _res result_type; };  // let _weak_result_type_impl perform the real work. template<typename _functor,          bool = is_member_function_pointer<_functor>::value>   struct _weak_result_type_memfun   : _weak_result_type_impl<_functor>   { };  // a pointer to member function has a weak result type. template<typename _memfunptr>   struct _weak_result_type_memfun<_memfunptr, true>   {     using result_type = typename _mem_fn_traits<_memfunptr>::__result_type;   };  // a pointer to data member doesn't have a weak result type. template<typename _func, typename _class>   struct _weak_result_type_memfun<_func _class::*, false>   { };  /**  *  strip top-level cv-qualifiers from the function object and let  *  _weak_result_type_memfun perform the real work. */ template<typename _functor>   struct _weak_result_type   : _weak_result_type_memfun<typename remove_cv<_functor>::type>   { };  /**  *  derives from unary_function or binary_function when it  *  can. specializations handle all of the easy cases. the primary  *  template determines what to do with a class type, which may  *  derive from both unary_function and binary_function. */ template<typename _tp>   struct _reference_wrapper_base   : _weak_result_type<_tp>, _refwrap_base_arg1<_tp>, _refwrap_base_arg2<_tp>   { };  // - a function type (unary) template<typename _res, typename _t1 _glibcxx_noexcept_parm>   struct _reference_wrapper_base<_res(_t1) _glibcxx_noexcept_qual>   : unary_function<_t1, _res>   { };  template<typename _res, typename _t1>   struct _reference_wrapper_base<_res(_t1) const>   : unary_function<_t1, _res>   { };  template<typename _res, typename _t1>   struct _reference_wrapper_base<_res(_t1) volatile>   : unary_function<_t1, _res>   { };  template<typename _res, typename _t1>   struct _reference_wrapper_base<_res(_t1) const volatile>   : unary_function<_t1, _res>   { };  // - a function type (binary) template<typename _res, typename _t1, typename _t2 _glibcxx_noexcept_parm>   struct _reference_wrapper_base<_res(_t1, _t2) _glibcxx_noexcept_qual>   : binary_function<_t1, _t2, _res>   { };  template<typename _res, typename _t1, typename _t2>   struct _reference_wrapper_base<_res(_t1, _t2) const>   : binary_function<_t1, _t2, _res>   { };  template<typename _res, typename _t1, typename _t2>   struct _reference_wrapper_base<_res(_t1, _t2) volatile>   : binary_function<_t1, _t2, _res>   { };  template<typename _res, typename _t1, typename _t2>   struct _reference_wrapper_base<_res(_t1, _t2) const volatile>   : binary_function<_t1, _t2, _res>   { };  // - a function pointer type (unary) template<typename _res, typename _t1 _glibcxx_noexcept_parm>   struct _reference_wrapper_base<_res(*)(_t1) _glibcxx_noexcept_qual>   : unary_function<_t1, _res>   { };  // - a function pointer type (binary) template<typename _res, typename _t1, typename _t2 _glibcxx_noexcept_parm>   struct _reference_wrapper_base<_res(*)(_t1, _t2) _glibcxx_noexcept_qual>   : binary_function<_t1, _t2, _res>   { };  template<typename _tp, bool = is_member_function_pointer<_tp>::value>   struct _reference_wrapper_base_memfun   : _reference_wrapper_base<_tp>   { };  template<typename _memfunptr>   struct _reference_wrapper_base_memfun<_memfunptr, true>   : _mem_fn_traits<_memfunptr>::__maybe_type   {     using result_type = typename _mem_fn_traits<_memfunptr>::__result_type;   }; 

不说了,看图:

引用传参与reference_wrapper

我的感受:

引用传参与reference_wrapper

大功告成

template<typename _tp>   class reference_wrapper   : public _reference_wrapper_base_memfun<typename remove_cv<_tp>::type>   {     _tp* _m_data;    public:     typedef _tp type;      reference_wrapper(_tp& __indata) noexcept     : _m_data(std::__addressof(__indata))     { }      reference_wrapper(_tp&&) = delete;      reference_wrapper(const reference_wrapper&) = default;      reference_wrapper&     operator=(const reference_wrapper&) = default;      operator _tp&() const noexcept     { return this->get(); }      _tp&     get() const noexcept     { return *_m_data; }      template<typename... _args>       typename result_of<_tp&(_args&&...)>::type       operator()(_args&&... __args) const       {         return std::__invoke(get(), std::forward<_args>(__args)...);       }   };  template<typename _tp>   inline reference_wrapper<_tp>   ref(_tp& __t) noexcept   { return reference_wrapper<_tp>(__t); }  template<typename _tp>   inline reference_wrapper<const _tp>   cref(const _tp& __t) noexcept   { return reference_wrapper<const _tp>(__t); }  template<typename _tp>   void ref(const _tp&&) = delete;  template<typename _tp>   void cref(const _tp&&) = delete;  template<typename _tp>   inline reference_wrapper<_tp>   ref(reference_wrapper<_tp> __t) noexcept   { return __t; }  template<typename _tp>   inline reference_wrapper<const _tp>   cref(reference_wrapper<_tp> __t) noexcept   { return { __t.get() }; } 

最后组装一下就好啦!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/599743.html

(0)
上一篇 2021年5月9日
下一篇 2021年5月9日

精彩推荐