Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do boost operators work?

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?

like image 736
fredoverflow Avatar asked Jun 02 '10 13:06

fredoverflow


1 Answers

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; }
};
like image 161
JoeG Avatar answered Sep 25 '22 01:09

JoeG