【问题标题】:How does boost bind work behind the scenes in general?一般来说,boost bind 在幕后是如何工作的?
【发布时间】:2010-09-11 21:09:32
【问题描述】:

无需花很长时间查看 boost 源代码,有人可以快速了解一下 boost 绑定是如何实现的吗?

【问题讨论】:

    标签: c++ boost boost-bind


    【解决方案1】:

    顺便说一句,如果 bind_t 通过包含 boost/bind/bind_template.hpp 被折叠和简化,它会变得更容易理解,如下所示:

    template<class R, class F, class L> 
    class bind_t
    {
        public:
    
            typedef bind_t this_type;
    
            bind_t(F f, L const & l): f_(f), l_(l) {}
    
            typedef typename result_traits<R, F>::type result_type;
            ...
            template<class A1> 
                result_type operator()(A1 & a1)
                {
                    list1<A1 &> a(a1);
                    return l_(type<result_type>(), f_, a, 0);
                }
        private:
            F f_;
            L l_;
    
    };
    

    【讨论】:

      【解决方案2】:

      我喜欢bind 来源的这一段:

      template<class R, class F, class L> class bind_t
      {
      public:
      
          typedef bind_t this_type;
      
          bind_t(F f, L const & l): f_(f), l_(l) {}
      
      #define BOOST_BIND_RETURN return
      #include <boost/bind/bind_template.hpp>
      #undef BOOST_BIND_RETURN
      
      };
      

      告诉你几乎所有你需要知道的,真的。

      bind_template 标头扩展为内联 operator() 定义列表。比如最简单的:

      result_type operator()()
      {
          list0 a;
          BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
      }
      

      此时我们可以看到BOOST_BIND_RETURN 宏扩展为return,因此该行更像return l_(type...)

      一个参数版本在这里:

      template<class A1> result_type operator()(A1 & a1)
      {
          list1<A1 &> a(a1);
          BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
      }
      

      很相似。

      listN 类是参数列表的包装器。这里有很多深奥的魔法,虽然我不太了解。他们还重载了调用神秘的unwrap 函数的operator()。忽略一些编译器特定的重载,它并没有做很多事情:

      // unwrap
      
      template<class F> inline F & unwrap(F * f, long)
      {
          return *f;
      }
      
      template<class F> inline F & unwrap(reference_wrapper<F> * f, int)
      {
          return f->get();
      }
      
      template<class F> inline F & unwrap(reference_wrapper<F> const * f, int)
      {
          return f->get();
      }
      

      命名约定似乎是:Fbind 的函数参数的类型。 R 是返回类型。 L 往往是参数类型的列表。还有很多复杂性,因为对于不同数量的参数有不少于九个重载。最好不要过多关注。

      【讨论】:

      • 这对我来说似乎并不简单......为什么#define BOOST_BIND_RETURN return 是必要的?为什么不直接返回?
      • 我还是不明白。 bind_t 调用构造函数是什么?
      • @Ha11owed 因为这样他们就可以将标头用于没有返回值的模板!
      【解决方案3】:

      我认为它是一个模板类,它为要绑定的参数声明一个成员变量,并为其余的参数重载 ()。

      【讨论】:

        猜你喜欢
        • 2010-10-06
        • 2017-08-13
        • 1970-01-01
        • 1970-01-01
        • 2014-04-06
        • 2010-09-24
        • 1970-01-01
        • 2023-04-07
        相关资源
        最近更新 更多