std::bind接口與實現

前言

最近想起半年前鴿下來的Haskell,重溫了一下忘得精光的語法,讀了幾個示例程序,挺帶感的,因而函數式編程的草就種得更深了。又去Google了一下C++與FP,找到了一份近乎完美的講義,而後被帶到C++20的ranges library,對即將發佈的C++20滿懷憧憬。此時,我猛然間意識到,看別人作,以爲本身也能作好,在遊戲界叫雲玩家,在編程界就叫雲程序員啊!html

不行,得找點事幹。想起一樣被我鴿了好久的<functional>系列,恰好與函數式編程搭點邊,就動筆寫吧!這就是本文的來歷。ios

找來GCC 8.1.0的標準庫,在<functional>中找到了std::bind的實現。花了好長時間終於讀懂了,原來std::bind的原理一點都不復雜。此外,std::bind的實現依賴於std::tuple,本文理應從後者開始講起,可是又看了看<tuple>的長度和難度,寫std::tuple未免喧賓奪主了。因此,本文將聚焦於std::bind的實現,其餘標準庫組件就當現成的來用了。c++

接口

你能點開這篇文章,說明你必定明白std::bind是幹什麼用的,以及應該怎麼用,我就不贅述了。簡而言之,std::bind用於給一個可調用對象綁定參數。可調用對象包括函數對象(仿函數)、函數指針、函數引用、成員函數指針和數據成員指針。綁定的參數能夠是實際的參數,也能夠是std::placeholders::_1等佔位符。std::bind返回一個函數對象,稱爲「bind表達式」,它被調用時,先前綁定的可調用對象被調用,參數爲在std::bind中綁定的參數,佔位符用調用函數對象時傳入的參數替換,_1表示第一個參數,從1開始計數。調用時多餘的參數會被求值而後忽略。程序員

很抽象吧?看個例子:express

#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返回的函數對象時傳入的參數。app

有三個你可能不知道的細節:less

  1. 調用可調用對象時,綁定參數被std::move,調用參數被std::forward,你得根據可調用對象的行爲來判斷std::bind返回的函數對象是否能夠屢次調用。socket

  2. 綁定參數能夠是bind表達式,佔位符被替換爲外層的調用參數,至關於用調用參數來調用這個bind表達式,求值後用來調用外層bind表達式——我是在讀源碼讀到一半一臉懵逼的時候才知道這件事的。這與可調用對象被std::bind之後能夠再std::bind並不衝突,由於bind表達式一個是做爲綁定參數,另外一個是做爲可調用對象。ide

  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、一、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。

相關文章
相關標籤/搜索