Boost logo

Boost Users :

Subject: [Boost-users] [Units] unary minus on units is counter intuitive (or a bug)
From: alfC (alfredo.correa_at_[hidden])
Date: 2010-11-30 02:50:27


Hi,

 I found this counterintuitive result of applying the unary minus
operator to a unit

"- si::meter" is the same as "si::meter" (or any other unit).

or worst

 std::cout << - si::meter*1. << std::endl; // prints 1*m

i.e. the minus is explicitly ignored. The root of the problem is this
curious line in boost/units/unit.hpp

/// unit runtime unary minus
template<class Dim,class System>
typename unary_minus_typeof_helper< unit<Dim,System> >::type
operator-(const unit<Dim,System>&)
{
    typedef typename unary_minus_typeof_helper< unit<Dim,System>
>::type type;

    return type();
}

a more intuitive result (but not completely elegant) could be attained
by defining instead:

template<class Dimension, class System>
quantity<unit<Dim, System> >
operator-(unit<Dim, System> const& u){
        return -1.*u;
}

This is a definition that I could add BUT it will conflict with the
original definition. Another way, could be to specialize
unary_minus_typeof_helper<...>::type to be something that is not a
unit but holds the negative "direction" and the cast to Type(-1)*unit
quantity but it seems overly complicated for the purpose.

Note aside: Why would I need "minus units" in the first place? The
original code that produced the confusion was

 - kB*T

which appears commonly in physics. kB is the "atomic" unit of entropy/
specific heat (atomic::heat_capacity) and T is a temperature quantity.
This was parsed as

 (-kB)*T and then as kB*T

i.e. the minus sign was ignored all together.

In my opinion unary operator- should not be defined for units in the
first place. The current definition only makes things worst, by
creating a counter intuitive result AND making the fix conflict with
the definition.

Thoughts?

Thank you,
Alfredo


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net