Boost logo

Boost :

From: Andy Little (andy_at_[hidden])
Date: 2005-10-10 13:50:36


"Geoffrey Romer" <geoff.romer_at_[hidden]> wrote

> Would there be any interest in a library for attaching units (physical
> or otherwise) to numeric variables, so that the type system could
> enforce dimension- and unit-consistency in all calculations, and
> convert semi-automatically between compatible units?
>
> To make this a little more concrete, here's a sketch of the kind of
> code such a library could enable:
>
> ---
> quantity<meters, double> distance(1.0);
> quantity<newtons, double> force(5.0);
>
> quantity<joules, double> work = distance * force;
> quantity<calories, double> work_cal = unit_cast<calories>(work);
> work_cal = work; //Compile error or implicit conversion,
> // possibly depending on compiler flag
> quantity<watts, double> power = work;
> //Compile error- incompatible types

In pqs http://www.servocomm.freeserve.co.uk/Cpp/physical_quantity/index.html it
would look like this:

    pqs::length::m distance(1.);
    pqs::force::N force(5.);
    pqs::energy::J work = distance * force;
// note: you would need to add calories of which according to the SI there are I
// think 6 varieties
//I opted to make automatic conversions between units...
    pqs::energy::cal work_cal = work;
    //pqs::power::W power = work ; //Compile error- incompatible types
    pqs::power::W power = work / pqs::time::s(1); //ok

> I know there's been a lot of discussion of units for a GUI library, so
> I'm especially interested in what people involved in that thread think
> of this idea- I want to make something sufficiently powerful to be
> useful in a context like that.

The problem with using physical units for a GUI is that they can make the code
rather inflexible. It is possible to template functions on the unit parameter
but this will cause code bloat. Far better to set a notional unit somewhere and
then have the ability to change the unit easily at runtime.

That said some applications can work only with one set of units because the
domain is fixed. e.g PCB design . In these cases it is helpful to users to
provide a set of user units(micrometers, millimeters, centimeters, inches) that
can be
converted to-from a standard unit for use by the application( probably
millimeters in the case of PCBs.)

regards
Andy Little


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk