Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Conversions

Conversion is only meaningful for quantities as it implies the presence of at least a multiplicative scale factor and, possibly, and affine linear offset. Macros for simplifying the definition of conversions between units can be found in boost/units/conversion.hpp and boost/units/absolute.hpp (for affine conversions with offsets).

The macro BOOST_UNITS_DEFINE_CONVERSION_FACTOR specifies a scale factor for conversion from the first unit type to the second. The first argument must be a base_unit. The second argument can be either a base_unit or a unit.

Let's declare a simple base unit:

struct foot_base_unit : base_unit<foot_base_unit, length_dimension, 10> { };

Now, we want to be able to convert feet to meters and vice versa. The foot is defined as exactly 0.3048 meters, so we can write the following

BOOST_UNITS_DEFINE_CONVERSION_FACTOR(foot_base_unit, meter_base_unit, double, 0.3048);

Alternately, we could use the SI length typedef:

BOOST_UNITS_DEFINE_CONVERSION_FACTOR(foot_base_unit, SI::length, double, 0.3048);

Since the SI unit of length is the meter, these two definitions are equivalent. If these conversions have been defined, then converting between scaled forms of these units will also automatically work.

The macro BOOST_UNITS_DEFAULT_CONVERSION specifies a conversion that will be applied to a base unit when no direct conversion is possible. This can be used to make arbitrary conversions work with a single specialization:

struct my_unit_tag : boost::units::base_unit<my_unit_tag, boost::units::force_type, 1> {};
// define the conversion factor
BOOST_UNITS_DEFINE_CONVERSION_FACTOR(my_unit_tag, SI::force, double, 3.14159265358979323846);
// make conversion to SI the default.
BOOST_UNITS_DEFAULT_CONVERSION(my_unit_tag, SI::force);

PrevUpHomeNext