代码之家  ›  专栏  ›  技术社区  ›  Brian R. Bondy

一般来说,boost bind是如何在幕后工作的?

  •  31
  • Brian R. Bondy  · 技术社区  · 16 年前

    如果不花很长时间检查Boost源代码,有人能给我一个关于Boost绑定是如何实现的简要说明吗?

    3 回复  |  直到 13 年前
        1
  •  24
  •   1800 INFORMATION    16 年前

    我喜欢这件 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 功能。忽略某些特定于编译器的重载,它不会做很多工作:

    // 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();
    }
    

    命名约定似乎是: F 函数参数的类型 绑定 . R 是返回类型。 L 通常是参数类型的列表。还有很多复杂的问题,因为不同数量的参数至少有九个重载。最好不要过于沉溺于此。

        2
  •  2
  •   Decoder    15 年前

    顺便说一下,如果 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_;
    
    };
    
        3
  •  0
  •   Lou Franco    16 年前

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