Monday, June 26, 2006

C++ Tip: dimnum - C++ classes for storage and manipulation of dimensionful numbers

dimnum documentation

Dimnum is a library for handling measurement units. Unit conversions and correctness checks are done at compile time. This is a very nice way to ensure that units don't get screwed up when writing simulations.

However, the documentation for this library is a bit lacking. So, here follows a brief example of how to use it. In this example, a unit type that is included by default is created and a simple calculation is done to show the output.

#include <dimnum/dimnum.hh>
#include <dimnum/si.hh>

// Create a dimensional base for force
namespace dimension {
  typedef powers<1, 1, -2, 0, 0, 0, 0> force;

// declare unit used for force
default(si, force, newton, 1, 1, 0, "N");

// create the unit abbreviations
// library bug - this should be done automatically
const char unit::meter::abbr[] = "m";
const char unit::newton::abbr[] = "N";
const char unit::joule::abbr[] = "J";

int main()
  si::length<double> l(3.0); // 3 meters
  si::force<double> f(10.0); // 10 newtons

  // output 3m x 10N
  // The first result is in SI base units
  // The second result is in the SI derived unit, Joule
  std::cout << l << " x " << f << " = " << l * f << " = " << si::energy<double>(l * f) << std::endl;

While useful, it should be noted that there are three small problems: the documentation is sparse, unit abbreviations need to be created for all the units used and there aren't many units available by default. However, given how increadably useful this is, those little problems shouldn't be reasons not to use this library.

No comments:

Post a Comment