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?
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; }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With