views:

88

answers:

1

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?

+3  A: 

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; }
};
Joe Gauterin
What's really fun is that you inherit privately from the class and yet it works. It's a funny trick really :)
Matthieu M.
It has a name: the [Barton-Nackman trick](http://en.wikipedia.org/wiki/Barton-Nackman_trick).
Rob Kennedy