Casting boost::units::quantity to double
Asked Answered
O

3

6

I need to pass the value of a quantity to a library for evaluation. The boost units library takes double values in SI, so the boost units library is very appealing in ensuring that requirement. However, how should I cast the quantity to a double value? The documentation and example seems to avoid this since the intent is to, rightfully so, maintain the units.

Something like:

quantity<pressure> p(101.1 * kilo * pascals);
double dblP = static_cast<double>(p);  // double value in Pascals 

Going through the headers suggests... Is that the correct way to cast to the base type?

p.value();
Ossy answered 18/12, 2012 at 16:10 Comment(2)
"Going through the headers suggests... p.value()" So your question is?Undershot
Good point - sorry I added that after the question was first asked. What I want to ensure is .value() does return what I expect reliably. Ie, is it after any needed conversions such as psi to Pa?Ossy
U
5

The reference documentation shows that either implicit casts or the value() member method can be used.

  1. operator value_type() const;

    implicit conversion to value_type is allowed

  2. const value_type & value() const;

    constant accessor to value

Undershot answered 18/12, 2012 at 16:54 Comment(2)
Thank you, that reference is very helpful (and hard to find with keywords quantity unit boost cast)Ossy
operator value_type() const; only exists for dimensionless quantites. Otherwise this would be possible: double v = quantity<si::length>().Charcoal
D
9

I think what you're looking for is this:

quantity<pressure> p(101.1 * kilo * pascals);
double dblP = p / pascals;  // double value in Pascals 

If you divide out the unit, you are left with a quantity<dimensionless> which will implicitly convert to a double. This eliminates any question of what the internal representation (which value() returns) units are.

Derrek answered 11/11, 2013 at 22:19 Comment(0)
K
7

Just spotted this. I think the intended method is to use Boost's quantity_cast operator.

quantity<pressure> p(101.1 * kilo * pascals);
double dblP = quantity_cast<double>(p);

http://www.boost.org/doc/libs/1_55_0/doc/html/boost_units/Quantities.html#boost_units.Quantities.Quantity_Construction_and_Conversion

Ketchan answered 9/2, 2014 at 12:59 Comment(0)
U
5

The reference documentation shows that either implicit casts or the value() member method can be used.

  1. operator value_type() const;

    implicit conversion to value_type is allowed

  2. const value_type & value() const;

    constant accessor to value

Undershot answered 18/12, 2012 at 16:54 Comment(2)
Thank you, that reference is very helpful (and hard to find with keywords quantity unit boost cast)Ossy
operator value_type() const; only exists for dimensionless quantites. Otherwise this would be possible: double v = quantity<si::length>().Charcoal

© 2022 - 2024 — McMap. All rights reserved.