|
Boost Users : |
Subject: Re: [Boost-users] [Units] help with type-safe unit-specific conversions
From: Matthias Schabel (boost_at_[hidden])
Date: 2009-07-22 16:57:02
Presumably these external libraries expect their input to be in a
specific unit. For maximal safety, you should use explicit
construction of that unit in a wrapper. So, for example, you have some
external function (not tested) :
void doSomethingWithLength(double length /* expects meters */);
create a wrapper function that expects a quantity (you could improve
this by only overloading on units with length dimensionality)
namespace wrap {
template<Unit>
void doSomethingWithLength(const quantity<Unit>& q)
{
return doSomethingWithLength((quantity<si::length>(q)).value());
}
} // namespace wrap
Then you can call wrap::doSomethingWithLength with any unit having
length dimension and the argument will be converted to meters and
"demarshalled"...
Matthias
> I have been playing with Boost.Units as part of a work project
> recently, and I am not sure what the best approach to
> "demarshalling" values in a specific unit. For example, I would
> like to do something like:
>
> using namespace boost::units;
>
> struct A {
> enum { feet, kilometers };
>
> quantity<si::length> some_length;
>
> double foo(int type) {
> switch(type) {
> case feet:
> return quantity<feet>(some_length).value();
> case kilometers:
> return quantity<kilometers>(some_length).value();
> }
> }
> };
>
> This approach is necessary for passing values to external libraries
> which do not (and probably will never) use Boost.Units. Is
> conversion_factor the best approach, or is there a way to achieve
> this implicitly using the type system?
>
> Thanks
> Justin
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net