std::bind介面與實現

来源:https://www.cnblogs.com/jerry-fuyi/archive/2020/04/05/12633621.html
-Advertisement-
Play Games

前言 最近想起半年前鴿下來的Haskell,重溫了一下忘得精光的語法,讀了幾個示常式序,挺帶感的,於是函數式編程的草就種得更深了。又去Google了一下C++與FP,找到了一份近乎完美的講義,然後被帶到C++20的ranges library,對即將發佈的C++20滿懷憧憬。此時,我猛然間意識到,看 ...


前言

最近想起半年前鴿下來的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。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • from wordcloud import WordCloud import matplotlib.pyplot as plt import jieba # 生成詞雲 def create_word_cloud(filename): with open('hongloumong.txt',encod ...
  • 為什麼要寫STL淺談這個系列,因為最近我在準備藍橋杯,刷題的時候經常要用到STL,準備補一補,但一直沒有找到一個好的視頻和資料,最開始準備跟著c語言中文網學,但覺得太繁雜了,最後在b站(b站上電腦類的教學視頻挺多的)上找了一個視頻學的。這個系列相當於我的一個整理。 這個系列只是淺談,但刷題應該夠了 ...
  • 這是我的第一篇隨筆,當然是發我寫的第一個游戲啦! 大一(本人現在大二)寒假過完年,在家待著想起放假前計劃寫一個游戲的,因為本人立志走游戲開發這條路,加上大一上冊學了C語言,就想寫個游戲練練手。想了很久,最後決定寫一個俄羅斯方塊。 萬事開頭難,一開始真的不知道從何下手,所以百度查了一些資料(程式猿必須 ...
  • 1. web.xml中url pattern配置 url pattern為/ 使用SpringMVC的框架時,需要在 配置前端控制器 ,配置為: url pattern為/ 我們需要使用過濾器時,需要在 中進行註冊。以處理中文亂碼的過濾器 為例,配置為: url pattern為 .do 使用Str ...
  • [TOC] pandas可以進行數據輸入和輸出,有以下幾種類型:讀取文本文件及硬碟上其他更高效的格式文件,從資料庫中載入數據,於網路資源進行交互(比如Web API)。 下麵進行不同文本文件的讀取和寫入操作講解,首先進行文本格式數據的讀寫講解。 一:文本格式數據的讀寫 將表格型數據讀取為DataFr ...
  • 原文: "Java Garbage Collection Algorithms [till Java 9]" 垃圾回收(Garbage collection,GC)一直是 Java 流行背後的重要特性之一。垃圾回收是 Java 中用於釋放未使用記憶體的機制。本質上,它跟蹤所有仍在使用的對象,並將其餘的 ...
  • 前言 AQS一共花了5篇文章,對裡面實現的核心源碼都做了註解 也和大家詳細描述了下,後面的幾篇文字我將和大家聊聊一下AQS的實際使用,主要會聊幾張鎖,第一篇我會和大家聊下ReentrantLock 重入鎖,雖然在講AQS中也穿插了講了一下,但是我還是深入的聊下 ==PS:前面5篇寫在了CSDN裡面 ...
  • SpringCloud版本:Finchley.SR2 SpringBoot版本:2.0.3.RELEASE 源碼地址:https://gitee.com/bingqilinpeishenme/Java Tutorials 前言 寫博客一個多月了,斷斷續續的更新,今天有小伙伴催更新了,很高興,說明我的 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...