boost 运算符如何工作?

发布于 2024-09-04 02:37:35 字数 407 浏览 4 评论 0原文

boost::operators 基于 += 等手动实现自动定义 + 等运算符,这非常有用。要为 T 生成这些运算符,需要继承 boost::operators,如 boost 示例所示:

class MyInt : boost::operators;

我熟悉 CRTP 模式,但我不明白它在这里是如何工作的。具体来说,我并没有真正继承任何设施,因为操作员不是成员。 boost::operators 似乎完全是空的,但我不太擅长阅读 boost 源代码。

谁能详细解释一下这是如何工作的?这种机制是否众所周知并广泛使用?

boost::operators automatically defines operators like + based on manual implementations like += which is very useful. To generate those operators for T, one inherits from boost::operators<T> as shown by the boost example:

class MyInt : boost::operators<MyInt>

I am familiar with the CRTP pattern, but I fail to see how it works here. Specifically, I am not really inheriting any facilities since the operators aren't members. boost::operators seems to be completely empty, but I'm not very good at reading boost source code.

Could anyone explain how this works in detail? Is this mechanism well-known and widely used?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滥情稳全场 2024-09-11 02:37:35

有一个很大的多重继承链,在其顶部有许多实现运算符的类,但它们是作为 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; }
};

There's a big multiple inheritance chain, at the top of which there are a number of classes that implement the operators, but do so as friend functions, thus placing them in the enclosing namespace rather than as members of the class.

For example, the final implementation of operator+ becomes:

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; }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文