代码之家  ›  专栏  ›  技术社区  ›  fredoverflow

boost操作符是如何工作的?

  •  16
  • fredoverflow  · 技术社区  · 16 年前

    boost::operators 自动定义运算符,如 + += T ,一个继承自 boost::operators<T>

    class MyInt : boost::operators<MyInt>

    我很熟悉CRTP模式,但是我不知道它在这里是如何工作的。具体来说,我没有真正继承任何设施,因为操作符不是成员。 boost::运算符

    有人能详细解释一下这是怎么回事吗?这一机制是否广为人知并得到广泛应用?

    1 回复  |  直到 16 年前
        1
  •  15
  •   JoeG    16 年前

    有一个很大的多重继承链,在这个链的顶部有许多实现操作符的类,但它们是按 friend 函数,从而将它们放置在封闭的命名空间中,而不是作为类的成员。

    operator+ 变成:

    template <class T, class U, class B = ::boost::detail::empty_base<T> >
    struct addable2 : B
    {                                                                  
      friend T operator +( T lhs, const U& rhs ) { return lhs += rhs; }
      friend T operator +( const U& lhs, T rhs ) { return rhs += lhs; }
    };