Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

THE BOOST MPL LIBRARY: Implementing Addition and Subtraction
Front Page / Tutorial: Metafunctions and Higher-Order Metaprogramming / Dimensional Analysis / Implementing Addition and Subtraction

Implementing Addition and Subtraction

We can now easily write the rules for addition and subtraction, since the dimensions of the arguments must always match.

template 
quantity
operator+(quantity x, quantity y)
{
  return quantity(x.value() + y.value());
}

template 
quantity
operator-(quantity x, quantity y)
{
  return quantity(x.value() - y.value());
}

These operators enable us to write code like:

quantitylength> len1( 1.0f );
quantitylength> len2( 2.0f );

len1 = len1 + len2;   // OK

but prevent us from trying to add incompatible dimensions:

len1 = len2 + quantitymass>( 3.7f ); // error