2

If I just want to convert a value from one unit to another, what's the simplest (ideally one-line) way of doing this?

For instance, i want to store a value in meters, but specify it in miles.

Most examples for doing this seem to be many lines long, involve typedefs and unit definitions, and don't give a simple unitless output.

Riot
  • 15,723
  • 4
  • 60
  • 67

2 Answers2

6

hmmm - I use the following.

#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/base_units/imperial/mile.hpp>

using namespace boost::units;

quantity<si::length> distance_in_metres = static_cast<quantity<si::length> >(
    100.0 * boost::units::imperial::mile_base_unit::unit_type()
);

FYI - I made a tutorial presentation on Boost Units at CPPcon 2015 - you can find it at https://www.youtube.com/watch?v=qphj8ZuZlPA

Community
  • 1
  • 1
Robert Ramey
  • 1,114
  • 8
  • 16
  • is the static cast necessary because of the potential loss of precision? – nimble_ninja Jan 24 '18 at 23:25
  • si::length is the length in meters. 100.0 * boost::units::imperial::mile_base_unit::unit_type() is a number of miles. The static cast converts the number of miles to a length quantity which happens to be measured in meters. – Robert Ramey Jan 26 '18 at 00:32
3

There are two ways of doing this quickly and easily.

Say you want to convert 100 miles to metres...

The first explicitly constructs a quantity:

#include <boost/units/quantity.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/base_units/imperial/mile.hpp>
double distance_in_metres = boost::units::quantity<boost::units::si::length>(
    100.0 * boost::units::imperial::mile_base_unit::unit_type()
  ) / boost::units::si::meter;

The second creates a conversion factor and multiplies by that:

#include <boost/units/systems/si/length.hpp>
#include <boost/units/base_units/imperial/mile.hpp>
double distance_in_metres = 100.0 *
  boost::units::conversion_factor(
    boost::units::imperial::mile_base_unit::unit_type(),
    boost::units::si::meter
  );
Riot
  • 15,723
  • 4
  • 60
  • 67