gpt4 book ai didi

c++ - Boost 运算符如何工作?

转载 作者:IT老高 更新时间:2023-10-28 22:21:19 26 4
gpt4 key购买 nike

boost::operators自动定义运算符,如 +基于手动实现,如 +=这是非常有用的。为 T 生成这些运算符, 一个继承自 boost::operators<T>如 boost 示例所示:

class MyInt : boost::operators<MyInt>

我熟悉 CRTP 模式,但我看不到它在这里是如何工作的。具体来说,我并没有真正继承任何设施,因为运营商不是成员。 boost::operators好像完全是空的,但是我不是很擅长阅读boost源代码。

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

最佳答案

有一个大的多重继承链,在它的顶部有许多实现运算符的类,但这样做是 friend 函数,因此将它们放置在封闭的命名空间中,而不是作为类(class)成员。

比如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; }
};

关于c++ - Boost 运算符如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2958142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com