c/c++语言开发共享std::bind接口与实现

前言 最近想起半年前鸽下来的Haskell,重温了一下忘得精光的语法,读了几个示例程序,挺带感的,于是函数式编程的草就种得更深了。又去Google了一下C++与FP,找到了一份近乎完美的讲义,然后被带到C++20的ranges library,对即将发布的C++20满怀憧憬。此时,我猛然间意识到,看 …


前言

最近想起半年前鸽下来的haskell,重温了一下忘得精光的语法,读了几个示例程序,挺带感的,于是函数式编程的草就种得更深了。又去google了一下c++与fp,找到了一份,然后被带到c++20的ranges library,对即将发布的c++20满怀憧憬。此时,我猛然间意识到,看别人做,觉得自己也能做好,在游戏界叫云玩家,在编程界就叫云程序员啊!

不行,得找点事干。想起同样被我鸽了很久的系列,刚好与函数式编程搭点边,就动笔写吧!这就是c/c++开发分享std::bind接口与实现的来历。

找来gcc 8.1.0的标准库,在<functional>中找到了std::bind的实现。花了好长时间终于读懂了,原来std::bind的原理一点都不复杂。此外,std::bind的实现依赖于std::tuple,c/c++开发分享std::bind接口与实现理应从后者开始讲起,但是又看了看<tuple>的长度和难度,写std::tuple未免喧宾夺主了。所以,c/c++开发分享std::bind接口与实现将聚焦于std::bind的实现,其他标准库组件就当现成的来用了。

接口

你能点开这篇文章,说明你一定明白std::bind是干什么用的,以及应该怎么用,我就不赘述了。简而言之,std::bind用于给一个可调用对象绑定参数。可调用对象包括函数对象(仿函数)、函数指针、函数引用、成员函数指针和数据成员指针。绑定的参数可以是实际的参数,也可以是std::placeholders::_1等占位符。std::bind返回一个函数对象,称为“bind表达式”,它被调用时,先前绑定的可调用对象被调用,参数为在std::bind中绑定的参数,占位符用调用函数对象时传入的参数替换,_1表示第一个参数,从1开始计数。调用时多余的参数会被求值然后忽略。

很抽象吧?看个例子:

#include <functional> using namespace std::placeholders;  void f(int a, int b, int c, int d) { }  int main() {     auto g = std::bind(f, 42, _2, _1, 233);     g(404, 10086, 114514); } 

这相当于调用f(42, 10086, 404, 233);

我终究还是赘述了,那就让赘述有点意义吧。明确两个概念:绑定参数,指调用std::bind时传入的除第一个可调用对象以外的参数;调用参数,指调用std::bind返回的函数对象时传入的参数。

有三个你可能不知道的细节:

  1. 调用可调用对象时,绑定参数被std::move,调用参数被std::forward,你得根据可调用对象的行为来判断std::bind返回的函数对象是否可以多次调用。

  2. 绑定参数可以是bind表达式,占位符被替换为外层的调用参数,相当于用调用参数来调用这个bind表达式,求值后用来调用外层bind表达式——我是在读源码读到一半一脸懵逼的时候才知道这件事的。这与可调用对象被std::bind以后可以再std::bind并不冲突,因为bind表达式一个是作为绑定参数,另一个是作为可调用对象。

  3. std::bind有个重载,可以用模板参数指定bind表达式的operator()的返回类型。

下面的程序演示了后两个功能:

#include <iostream> #include <functional> using namespace std::placeholders;  class a { public:     a(int i) : i(i) { }     friend std::ostream& operator<<(std::ostream&, const a&); private:     int i; };  std::ostream& operator<<(std::ostream& os, const a& a) {     os << "a: " << a.i;     return os; }  int main() {     auto f = std::bind<a>(std::plus<int>(), 1, std::bind(std::multiplies<int>(), 2, _1));     std::cout << f(3) << std::endl; } 

程序输出a: 7

还有两个type traits:std::is_bind_expression,对std::bind的返回类型其valuetruestd::is_placeholder,对std::placeholders::_1的类型其value1,以此类推。

实现

终于步入正题了。std::bind的实现原理并不复杂,但是标准库要考虑各种奇葩情况,比如volatile和可变参数(如std::printf,而非变参模板)等,代码就变长了很多(典型的有)。

为了讲解与理解的方便,我把std::bind的实现分成5个层次:

  1. 工具:is_bind_expressionis_placeholdernamespace std::placeholders_safe_tuple_element_t__volget,前两个用于模板偏特化;

  2. _mu:4种情况,分类讨论;

  3. _bind_bind_bind_resultstd::bind的返回类型;

  4. 辅助:_bind_check_arity__is_socketlike_bind_helper_bindres_helper

  5. std::bind本尊。

总体上,_bind保存可调用对象和绑定参数,_mu把绑定参数转换为实际参数。

工具

  /**    *  @brief determines if the given type _tp is a function object that    *  should be treated as a subexpression when evaluating calls to    *  function objects returned by bind().    *    *  c++11 [func.bind.isbind].    *  @ingroup binders    */   template<typename _tp>     struct is_bind_expression     : public false_type { };    /**    *  @brief class template _bind is always a bind expression.    *  @ingroup binders    */   template<typename _signature>     struct is_bind_expression<_bind<_signature> >     : public true_type { };    /**    *  @brief class template _bind is always a bind expression.    *  @ingroup binders    */   template<typename _signature>     struct is_bind_expression<const _bind<_signature> >     : public true_type { };    /**    *  @brief class template _bind is always a bind expression.    *  @ingroup binders    */   template<typename _signature>     struct is_bind_expression<volatile _bind<_signature> >     : public true_type { };    /**    *  @brief class template _bind is always a bind expression.    *  @ingroup binders    */   template<typename _signature>     struct is_bind_expression<const volatile _bind<_signature>>     : public true_type { };    /**    *  @brief class template _bind_result is always a bind expression.    *  @ingroup binders    */   template<typename _result, typename _signature>     struct is_bind_expression<_bind_result<_result, _signature>>     : public true_type { };    /**    *  @brief class template _bind_result is always a bind expression.    *  @ingroup binders    */   template<typename _result, typename _signature>     struct is_bind_expression<const _bind_result<_result, _signature>>     : public true_type { };    /**    *  @brief class template _bind_result is always a bind expression.    *  @ingroup binders    */   template<typename _result, typename _signature>     struct is_bind_expression<volatile _bind_result<_result, _signature>>     : public true_type { };    /**    *  @brief class template _bind_result is always a bind expression.    *  @ingroup binders    */   template<typename _result, typename _signature>     struct is_bind_expression<const volatile _bind_result<_result, _signature>>     : public true_type { };      /** @brief the type of placeholder objects defined by libstdc++.    *  @ingroup binders    */   template<int _num> struct _placeholder { };    /** @namespace std::placeholders    *  @brief iso c++11 entities sub-namespace for functional.    *  @ingroup binders    */   namespace placeholders   {   /* define a large number of placeholders. there is no way to    * simplify this with variadic templates, because we're introducing    * unique names for each.    */     extern const _placeholder<1> _1;     extern const _placeholder<2> _2;     extern const _placeholder<3> _3;     extern const _placeholder<4> _4;     extern const _placeholder<5> _5;     extern const _placeholder<6> _6;     extern const _placeholder<7> _7;     extern const _placeholder<8> _8;     extern const _placeholder<9> _9;     extern const _placeholder<10> _10;     extern const _placeholder<11> _11;     extern const _placeholder<12> _12;     extern const _placeholder<13> _13;     extern const _placeholder<14> _14;     extern const _placeholder<15> _15;     extern const _placeholder<16> _16;     extern const _placeholder<17> _17;     extern const _placeholder<18> _18;     extern const _placeholder<19> _19;     extern const _placeholder<20> _20;     extern const _placeholder<21> _21;     extern const _placeholder<22> _22;     extern const _placeholder<23> _23;     extern const _placeholder<24> _24;     extern const _placeholder<25> _25;     extern const _placeholder<26> _26;     extern const _placeholder<27> _27;     extern const _placeholder<28> _28;     extern const _placeholder<29> _29;   }    /**    *  @brief determines if the given type _tp is a placeholder in a    *  bind() expression and, if so, which placeholder it is.    *    *  c++11 [func.bind.isplace].    *  @ingroup binders    */   template<typename _tp>     struct is_placeholder     : public integral_constant<int, 0>     { };    /**    *  partial specialization of is_placeholder that provides the placeholder    *  number for the placeholder objects defined by libstdc++.    *  @ingroup binders    */   template<int _num>     struct is_placeholder<_placeholder<_num> >     : public integral_constant<int, _num>     { };    template<int _num>     struct is_placeholder<const _placeholder<_num> >     : public integral_constant<int, _num>     { };    #if __cplusplus > 201402l   template <typename _tp> inline constexpr bool is_bind_expression_v     = is_bind_expression<_tp>::value;   template <typename _tp> inline constexpr int is_placeholder_v     = is_placeholder<_tp>::value; #endif // c++17      // like tuple_element_t but sfinae-friendly.   template<std::size_t __i, typename _tuple>     using _safe_tuple_element_t       = typename enable_if<(__i < tuple_size<_tuple>::value),                            tuple_element<__i, _tuple>>::type::type;      // std::get<i> for volatile-qualified tuples   template<std::size_t _ind, typename... _tp>     inline auto     __volget(volatile tuple<_tp...>& __tuple)     -> __tuple_element_t<_ind, tuple<_tp...>> volatile&     { return std::get<_ind>(const_cast<tuple<_tp...>&>(__tuple)); }    // std::get<i> for const-volatile-qualified tuples   template<std::size_t _ind, typename... _tp>     inline auto     __volget(const volatile tuple<_tp...>& __tuple)     -> __tuple_element_t<_ind, tuple<_tp...>> const volatile&     { return std::get<_ind>(const_cast<const tuple<_tp...>&>(__tuple)); } 

这里好像没什么值得讲解的呢,注释都写得很清楚啦。

_mu

  /**    *  maps an argument to bind() into an actual argument to the bound    *  function object [func.bind.bind]/10. only the first parameter should    *  be specified: the rest are used to determine among the various    *  implementations. note that, although this class is a function    *  object, it isn't entirely normal because it takes only two    *  parameters regardless of the number of parameters passed to the    *  bind expression. the first parameter is the bound argument and    *  the second parameter is a tuple containing references to the    *  rest of the arguments.    */   template<typename _arg,            bool _isbindexp = is_bind_expression<_arg>::value,            bool _isplaceholder = (is_placeholder<_arg>::value > 0)>     class _mu;    /**    *  if the argument is reference_wrapper<_tp>, returns the    *  underlying reference.    *  c++11 [func.bind.bind] p10 bullet 1.    */   template<typename _tp>     class _mu<reference_wrapper<_tp>, false, false>     {     public:       /* note: this won't actually work for const volatile        * reference_wrappers, because reference_wrapper::get() is const        * but not volatile-qualified. this might be a defect in the tr.        */       template<typename _cvref, typename _tuple>         _tp&         operator()(_cvref& __arg, _tuple&) const volatile         { return __arg.get(); }     };    /**    *  if the argument is a bind expression, we invoke the underlying    *  function object with the same cv-qualifiers as we are given and    *  pass along all of our arguments (unwrapped).    *  c++11 [func.bind.bind] p10 bullet 2.    */   template<typename _arg>     class _mu<_arg, true, false>     {     public:       template<typename _cvarg, typename... _args>         auto         operator()(_cvarg& __arg,                    tuple<_args...>& __tuple) const volatile         -> decltype(__arg(declval<_args>()...))         {           // construct an index tuple and forward to __call           typedef typename _build_index_tuple<sizeof...(_args)>::__type             _indexes;           return this->__call(__arg, __tuple, _indexes());         }      private:       // invokes the underlying function object __arg by unpacking all       // of the arguments in the tuple.       template<typename _cvarg, typename... _args, std::size_t... _indexes>         auto         __call(_cvarg& __arg, tuple<_args...>& __tuple,                const _index_tuple<_indexes...>&) const volatile         -> decltype(__arg(declval<_args>()...))         {           return __arg(std::get<_indexes>(std::move(__tuple))...);         }     };    /**    *  if the argument is a placeholder for the nth argument, returns    *  a reference to the nth argument to the bind function object.    *  c++11 [func.bind.bind] p10 bullet 3.    */   template<typename _arg>     class _mu<_arg, false, true>     {     public:       template<typename _tuple>         _safe_tuple_element_t<(is_placeholder<_arg>::value - 1), _tuple>&&         operator()(const volatile _arg&, _tuple& __tuple) const volatile         {           return             ::std::get<(is_placeholder<_arg>::value - 1)>(std::move(__tuple));         }     };    /**    *  if the argument is just a value, returns a reference to that    *  value. the cv-qualifiers on the reference are determined by the caller.    *  c++11 [func.bind.bind] p10 bullet 4.    */   template<typename _arg>     class _mu<_arg, false, false>     {     public:       template<typename _cvarg, typename _tuple>         _cvarg&&         operator()(_cvarg&& __arg, _tuple&) const volatile         { return std::forward<_cvarg>(__arg); }     }; 

_mu类模板用于转换绑定参数,该调用的调用,该替换的替换。_mu其实只起到函数模板的作用,但是函数模板不能偏特化,就只能写成类了。因此,_mu只有默认的构造函数,实例都是当即使用的(_mu<t>()(...))。

_mu有三个参数:_arg是一个绑定参数的类型;_isbindexp指示它是否是bind表达式,之前提到这里的bind表达式需要求值后才能使用,这是一种特殊情况;_isplaceholder指示它是否是一个占位符,占位符需要替换,这也是一种特殊情况。后两个参数用于偏特化,别处使用时只写第一个参数。

_mu<t>::operator()有统一的接口:第一个参数是_cvarg类型的,满足typename std::decay<_cvarg>::type等于_arg&&是通用引用,虽然_cvarg的类型是可以穷举的,但是写成模板就把左值、右值、constvolatile等情况一并处理掉了;第二个参数是_tuple类型,是调用参数转发组成的std::tuple

至于operator()要做什么工作,就要分情况讨论了:

  • 第一种情况,当_arg匹配到reference_wrapper<_tp>时,operator()要做的仅仅是把reference_wrapper包装的引用拿出来。

  • 第二种情况,_arg是bind表达式,把std::tuple展开后给它调用。

    展开过程挺有意思的。假设sizeof...(_args) == 3,类型_indexes就是_index_tuple<0, 1, 2>(这可以用模板元编程来实现),__call的模板参数_indexes0, 1, 2,对__arg的调用展开为:__arg(std::get<0>(std::move(__tuple)), std::get<1>(std::move(__tuple)), std::get<2>(std::move(__tuple))),3个参数的类型分别是(std::decay后)_tuple的第0、1、2个模板参数,刚好就是调用参数的类型,与接口相符。

    注意_arg_bind_bind_result的一个实例,这里只是去调用bind表达式,没有深入到里面的嵌套bind表达式和占位符替换(禁止套娃)。

  • 第三种情况,_arg是占位符,就返回调用参数中对应的那个。占位符从1开始编号,std::tuple从0开始编号,所以要减去1。当占位符超过调用参数数量时,比如绑定参数有_3而调用参数只有2个,std::get会报错(但是我没理解_safe_tuple_element_t的意义)。

  • 第四种情况,_arg啥都匹配不上,它就是一个普普通通的值,直接转发它即可。

_bind

  /// type of the function object returned from bind().   template<typename _signature>     struct _bind;     template<typename _functor, typename... _bound_args>     class _bind<_functor(_bound_args...)>     : public _weak_result_type<_functor>     {       typedef typename _build_index_tuple<sizeof...(_bound_args)>::__type         _bound_indexes;        _functor _m_f;       tuple<_bound_args...> _m_bound_args;        // call unqualified       template<typename _result, typename... _args, std::size_t... _indexes>         _result         __call(tuple<_args...>&& __args, _index_tuple<_indexes...>)         {           return std::__invoke(_m_f,               _mu<_bound_args>()(std::get<_indexes>(_m_bound_args), __args)...               );         }        // call as const       template<typename _result, typename... _args, std::size_t... _indexes>         _result         __call_c(tuple<_args...>&& __args, _index_tuple<_indexes...>) const         {           return std::__invoke(_m_f,               _mu<_bound_args>()(std::get<_indexes>(_m_bound_args), __args)...               );         }        // call as volatile       template<typename _result, typename... _args, std::size_t... _indexes>         _result         __call_v(tuple<_args...>&& __args,                  _index_tuple<_indexes...>) volatile         {           return std::__invoke(_m_f,               _mu<_bound_args>()(__volget<_indexes>(_m_bound_args), __args)...               );         }        // call as const volatile       template<typename _result, typename... _args, std::size_t... _indexes>         _result         __call_c_v(tuple<_args...>&& __args,                    _index_tuple<_indexes...>) const volatile         {           return std::__invoke(_m_f,               _mu<_bound_args>()(__volget<_indexes>(_m_bound_args), __args)...               );         }        template<typename _boundarg, typename _callargs>         using _mu_type = decltype(             _mu<typename remove_cv<_boundarg>::type>()(               std::declval<_boundarg&>(), std::declval<_callargs&>()) );        template<typename _fn, typename _callargs, typename... _bargs>         using _res_type_impl           = typename result_of< _fn&(_mu_type<_bargs, _callargs>&&...) >::type;        template<typename _callargs>         using _res_type = _res_type_impl<_functor, _callargs, _bound_args...>;        template<typename _callargs>         using __dependent = typename           enable_if<bool(tuple_size<_callargs>::value+1), _functor>::type;        template<typename _callargs, template<class> class __cv_quals>         using _res_type_cv = _res_type_impl<           typename __cv_quals<__dependent<_callargs>>::type,           _callargs,           typename __cv_quals<_bound_args>::type...>;       public:       template<typename... _args>         explicit _bind(const _functor& __f, _args&&... __args)         : _m_f(__f), _m_bound_args(std::forward<_args>(__args)...)         { }        template<typename... _args>         explicit _bind(_functor&& __f, _args&&... __args)         : _m_f(std::move(__f)), _m_bound_args(std::forward<_args>(__args)...)         { }        _bind(const _bind&) = default;        _bind(_bind&& __b)       : _m_f(std::move(__b._m_f)), _m_bound_args(std::move(__b._m_bound_args))       { }        // call unqualified       template<typename... _args,                typename _result = _res_type<tuple<_args...>>>         _result         operator()(_args&&... __args)         {           return this->__call<_result>(               std::forward_as_tuple(std::forward<_args>(__args)...),               _bound_indexes());         }        // call as const       template<typename... _args,                typename _result = _res_type_cv<tuple<_args...>, add_const>>         _result         operator()(_args&&... __args) const         {           return this->__call_c<_result>(               std::forward_as_tuple(std::forward<_args>(__args)...),               _bound_indexes());         }  #if __cplusplus > 201402l # define _glibcxx_depr_bind        [[deprecated("std::bind does not support volatile in c++17")]] #else # define _glibcxx_depr_bind #endif       // call as volatile       template<typename... _args,                typename _result = _res_type_cv<tuple<_args...>, add_volatile>>         _glibcxx_depr_bind         _result         operator()(_args&&... __args) volatile         {           return this->__call_v<_result>(               std::forward_as_tuple(std::forward<_args>(__args)...),               _bound_indexes());         }        // call as const volatile       template<typename... _args,                typename _result = _res_type_cv<tuple<_args...>, add_cv>>         _glibcxx_depr_bind         _result         operator()(_args&&... __args) const volatile         {           return this->__call_c_v<_result>(               std::forward_as_tuple(std::forward<_args>(__args)...),               _bound_indexes());         }     };    /// type of the function object returned from bind<r>().   template<typename _result, typename _signature>     struct _bind_result;    template<typename _result, typename _functor, typename... _bound_args>     class _bind_result<_result, _functor(_bound_args...)>     {       typedef typename _build_index_tuple<sizeof...(_bound_args)>::__type         _bound_indexes;        _functor _m_f;       tuple<_bound_args...> _m_bound_args;        // sfinae types       template<typename _res>         using __enable_if_void           = typename enable_if<is_void<_res>{}>::type;        template<typename _res>         using __disable_if_void           = typename enable_if<!is_void<_res>{}, _result>::type;        // call unqualified       template<typename _res, typename... _args, std::size_t... _indexes>         __disable_if_void<_res>         __call(tuple<_args...>&& __args, _index_tuple<_indexes...>)         {           return std::__invoke(_m_f, _mu<_bound_args>()                       (std::get<_indexes>(_m_bound_args), __args)...);         }        // call unqualified, return void       template<typename _res, typename... _args, std::size_t... _indexes>         __enable_if_void<_res>         __call(tuple<_args...>&& __args, _index_tuple<_indexes...>)         {           std::__invoke(_m_f, _mu<_bound_args>()                (std::get<_indexes>(_m_bound_args), __args)...);         }        // call as const       template<typename _res, typename... _args, std::size_t... _indexes>         __disable_if_void<_res>         __call(tuple<_args...>&& __args, _index_tuple<_indexes...>) const         {           return std::__invoke(_m_f, _mu<_bound_args>()                       (std::get<_indexes>(_m_bound_args), __args)...);         }        // call as const, return void       template<typename _res, typename... _args, std::size_t... _indexes>         __enable_if_void<_res>         __call(tuple<_args...>&& __args, _index_tuple<_indexes...>) const         {           std::__invoke(_m_f, _mu<_bound_args>()                (std::get<_indexes>(_m_bound_args),  __args)...);         }        // call as volatile       template<typename _res, typename... _args, std::size_t... _indexes>         __disable_if_void<_res>         __call(tuple<_args...>&& __args, _index_tuple<_indexes...>) volatile         {           return std::__invoke(_m_f, _mu<_bound_args>()                       (__volget<_indexes>(_m_bound_args), __args)...);         }        // call as volatile, return void       template<typename _res, typename... _args, std::size_t... _indexes>         __enable_if_void<_res>         __call(tuple<_args...>&& __args, _index_tuple<_indexes...>) volatile         {           std::__invoke(_m_f, _mu<_bound_args>()                (__volget<_indexes>(_m_bound_args), __args)...);         }        // call as const volatile       template<typename _res, typename... _args, std::size_t... _indexes>         __disable_if_void<_res>         __call(tuple<_args...>&& __args,                _index_tuple<_indexes...>) const volatile         {           return std::__invoke(_m_f, _mu<_bound_args>()                       (__volget<_indexes>(_m_bound_args), __args)...);         }        // call as const volatile, return void       template<typename _res, typename... _args, std::size_t... _indexes>         __enable_if_void<_res>         __call(tuple<_args...>&& __args,                _index_tuple<_indexes...>) const volatile         {           std::__invoke(_m_f, _mu<_bound_args>()                (__volget<_indexes>(_m_bound_args), __args)...);         }      public:       typedef _result result_type;        template<typename... _args>         explicit _bind_result(const _functor& __f, _args&&... __args)         : _m_f(__f), _m_bound_args(std::forward<_args>(__args)...)         { }        template<typename... _args>         explicit _bind_result(_functor&& __f, _args&&... __args)         : _m_f(std::move(__f)), _m_bound_args(std::forward<_args>(__args)...)         { }        _bind_result(const _bind_result&) = default;        _bind_result(_bind_result&& __b)       : _m_f(std::move(__b._m_f)), _m_bound_args(std::move(__b._m_bound_args))       { }        // call unqualified       template<typename... _args>         result_type         operator()(_args&&... __args)         {           return this->__call<_result>(               std::forward_as_tuple(std::forward<_args>(__args)...),               _bound_indexes());         }        // call as const       template<typename... _args>         result_type         operator()(_args&&... __args) const         {           return this->__call<_result>(               std::forward_as_tuple(std::forward<_args>(__args)...),               _bound_indexes());         }        // call as volatile       template<typename... _args>         _glibcxx_depr_bind         result_type         operator()(_args&&... __args) volatile         {           return this->__call<_result>(               std::forward_as_tuple(std::forward<_args>(__args)...),               _bound_indexes());         }        // call as const volatile       template<typename... _args>         _glibcxx_depr_bind         result_type         operator()(_args&&... __args) const volatile         {           return this->__call<_result>(               std::forward_as_tuple(std::forward<_args>(__args)...),               _bound_indexes());         }     }; #undef _glibcxx_depr_bind 

这一段就开始啰嗦了,但也没有办法,const加倍,volatile再加倍。有些地方还要考虑&&&noexcept,以至于不得不用宏来定义。还好c++只有这几个修饰符。

回到正题。_bind包含两个成员,可调用对象和绑定的参数,后者包在一个std::tuple中保存。构造函数把可调用对象拷贝或移动进来,绑定参数转发进来保存。_bind类支持拷贝和移动,行为都是默认的。

_bound_indexes_mu<_arg, true, false>中的_indexes相同,__call中的调用也与_mu<_arg, true, false>::operator()类似,不过不是用括号调用,而是用std::invoke,这把函数对象和成员指针等不同调用格式统一了起来。

有或没有cv修饰符的__calloperator()大体上相同,无非是参数和返回类型有些许区别。为了方便表示这些大同小异的类型,_bind类中定义了一些工具:

  • _mu_type把绑定参数类型转换为实际参数类型;

  • _res_type_impl定义返回类型,在不指定返回类型的std::bind中,返回类型是自动推导的;

  • _res_type定义可调用对象没有加cv修饰符时的返回类型;

  • _res_type_cv定义可调用对象加了cv修饰符时的返回类型。cv修饰符共有3种组合,_res_type_cv用模板参数__cv_quals来区分,模板里套模板,嗯,有内味了!我第一次见到这种操作时,跟当初学函数指针时一样激动——等等,__cv_quals不也是函数一样的东西作为参数吗?

定义好了这些类型,4种__calloperator()就很容易实现了,这在_mu的bind表达式的情况中已经分析过了。

_bind_result略有不同,既然返回类型已经规定好了,就不用各种定义了,但是又多出对void的讨论。在返回类型为void的函数中,你可以返回一个返回类型为void的表达式(但是不能直接return void;),但是你不能返回一个非void表达式,因此std::bind<void>是一种特殊情况,_bind_result_resultvoid需要专门的处理。

__enable_if_void__disable_if_void分别在_res是和不是void的时候有意义。每种__call函数都有两个,返回__disable_if_void<_res>的有return语句,另一个没有。对于特定的_result,两个函数中总是恰好有一个合法,根据sfinae,另一个被忽略,void的情况就是这么处理的。

辅助

  template<typename _func, typename... _boundargs>     struct _bind_check_arity { };    template<typename _ret, typename... _args, typename... _boundargs>     struct _bind_check_arity<_ret (*)(_args...), _boundargs...>     {       static_assert(sizeof...(_boundargs) == sizeof...(_args),                    "wrong number of arguments for function");     };    template<typename _ret, typename... _args, typename... _boundargs>     struct _bind_check_arity<_ret (*)(_args......), _boundargs...>     {       static_assert(sizeof...(_boundargs) >= sizeof...(_args),                    "wrong number of arguments for function");     };    template<typename _tp, typename _class, typename... _boundargs>     struct _bind_check_arity<_tp _class::*, _boundargs...>     {       using _arity = typename _mem_fn<_tp _class::*>::_arity;       using _varargs = typename _mem_fn<_tp _class::*>::_varargs;       static_assert(_varargs::value                     ? sizeof...(_boundargs) >= _arity::value + 1                     : sizeof...(_boundargs) == _arity::value + 1,                     "wrong number of arguments for pointer-to-member");     };      // trait type used to remove std::bind() from overload set via sfinae   // when first argument has integer type, so that std::bind() will   // not be a better match than ::bind() from the bsd sockets api.   template<typename _tp, typename _tp2 = typename decay<_tp>::type>     using __is_socketlike = __or_<is_integral<_tp2>, is_enum<_tp2>>;    template<bool _socketlike, typename _func, typename... _boundargs>     struct _bind_helper     : _bind_check_arity<typename decay<_func>::type, _boundargs...>     {       typedef typename decay<_func>::type __func_type;       typedef _bind<__func_type(typename decay<_boundargs>::type...)> type;     };    // partial specialization for is_socketlike == true, does not define   // nested type so std::bind() will not participate in overload resolution   // when the first argument might be a socket file descriptor.   template<typename _func, typename... _boundargs>     struct _bind_helper<true, _func, _boundargs...>     { };      template<typename _result, typename _func, typename... _boundargs>     struct _bindres_helper     : _bind_check_arity<typename decay<_func>::type, _boundargs...>     {       typedef typename decay<_func>::type __functor_type;       typedef _bind_result<_result,                            __functor_type(typename decay<_boundargs>::type...)>         type;     }; 

_bind_check_arity检查参数数量:当可调用对象是函数或类成员时,可以检查绑定参数与可调用对象需要的参数是否匹配;如果函数是变参的,绑定参数数量得大于等于函数参数数量;如果是类成员,还要加上1作为this指针。_bind_helper继承_bind_check_arity,实例化时会检查参数数量,如果错误的话编译器会输出static_assert错误,这样比较好看。(你敢直面模板错误吗?)

__is_socketlike用于消除重载:bsd套接字api中有::bind函数,其第一个参数是整型或枚举,不可能是可调用对象。当_bind_helper的第一个模板参数为true时,类中没有定义type类型,根据sfinae,bind调用匹配到::bind

bind

  /**    *  @brief function template for std::bind.    *  @ingroup binders    */   template<typename _func, typename... _boundargs>     inline typename     _bind_helper<__is_socketlike<_func>::value, _func, _boundargs...>::type     bind(_func&& __f, _boundargs&&... __args)     {       typedef _bind_helper<false, _func, _boundargs...> __helper_type;       return typename __helper_type::type(std::forward<_func>(__f),                                           std::forward<_boundargs>(__args)...);     }    /**    *  @brief function template for std::bind<r>.    *  @ingroup binders    */   template<typename _result, typename _func, typename... _boundargs>     inline     typename _bindres_helper<_result, _func, _boundargs...>::type     bind(_func&& __f, _boundargs&&... __args)     {       typedef _bindres_helper<_result, _func, _boundargs...> __helper_type;       return typename __helper_type::type(std::forward<_func>(__f),                                           std::forward<_boundargs>(__args)...);     } 

把可调用对象转发进_bind_bind_result并返回,这就是std::bind的工作。

展望

  1. 对c++的展望:lambda、std::functionstd::bind都是c++用以支持函数式范式的工具,而对数据的函数式处理,还需借由boost.range或在c++20中标准化的namespace std::ranges来完成。

  2. 对c/c++开发分享std::bind接口与实现的展望:

    • 正如前言所述,std::tuple的实现是std::bind的实现中的主体,我应该再开一篇来讲std::tuple的原理;

    • 对于一个想深入了解std::bind的读者来说,带着他欣赏源码可能不如手把手写一遍来得有效。我实现过、扩展过,可惜c++模板学艺不精,眼下还不能把实现中的每个细节都讲明白。很巧的是就在刚才,学校里的老师问我要删减的论文,被删减的附录中就包括一个std::function的扩展,等有机会再写吧。

  3. 对我的展望:学模板、学fp。

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

ctvol管理联系方式QQ:251552304

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

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

精彩推荐