Mixed units with boost::units

659 views Asked by At

In my program, I would like to take advantage of boost::units for type safe computations and automatic conversions. As a novice user of the library, I have a basic understanding of how it works, and why implicit type conversion is forbidden.

Right now I can write code like this

using namespace boost::units;
using namespace boost::units::si;

quantity<mass> my_mass(50 * kilogram);
quantity<force> my_force = my_mass * 9.81 * meter / pow<2>(second);

Where my_mass will be expressed in kilograms and my_force in Newton. But for convenience when interacting with other libraries which accept only double, I would prefer forces to be in kiloNewton (and, similarly, pressures in MegaPascal). So I do this:

typedef make_scaled_unit<force, scale<10, static_rational<3>>>::type kiloforce;
quantity<kiloforce> scaled_force(my_mass * 9.81 * meter / pow<2>(second));

Which works, but forces an explicit conversion. The following code, rightfully, does not compile:

quantity<kiloforce> scaled_force = my_mass * 9.81 * meter / pow<2>(second);

Because it represents an implicit conversion. My question is then: is there a way to configure the library so that quantities are expressed in the scaled unit of choice?

After all, this is the case for "kilogram", so I looked into scaled units, but I cannot seem to find a way to make it work. The idea would have been to define a custom system, but since mass, force and pressure are related to each other, this is not possible, as explained here.

1

There are 1 answers

2
MSalters On BEST ANSWER

The basic problem seems to be that you're looking for a dimensionless force in kilonewtons. That's not hard :

quantity<force> my_force = my_mass * 9.81 * meter / pow<2>(second);
double F = my_force / (kilo*newtons); // my_force in kN

The physics problem seems to be "kiloforce". That's not how physics works. Forces do not have prefixes, units do. E.g. length vs. meter/kilometer and mass vs gram/kilogram. Similarly, force vs Nnewton/kiloNewton.

That said, may I suggest

make_scaled_unit<acceleration, scale<10, static_rational<3>>>::type g(0.00981);

Don't ask me why you'd express the earth's acceleration in kilometers per second squared, but a kiloNewton is a kilometer kilogram per second squared.