Jerry @DOA&INPAC, SJTU

Working out everything from the first principles.

导航

std::bind接口与实现

前言

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

不行,得找点事干。想起同样被我鸽了很久的<functional>系列,刚好与函数式编程搭点边,就动笔写吧!这就是本文的来历。

找来GCC 8.1.0的标准库,在<functional>中找到了std::bind的实现。花了好长时间终于读懂了,原来std::bind的原理一点都不复杂。此外,std::bind的实现依赖于std::tuple,本文理应从后者开始讲起,但是又看了看<tuple>的长度和难度,写std::tuple未免喧宾夺主了。所以,本文将聚焦于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::is_function)。

为了讲解与理解的方便,我把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. 对本文的展望:

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

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

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

posted on 2020-04-05 19:16  Jerry_SJTU  阅读(3914)  评论(0编辑  收藏  举报