I have a very simple use case for using Boost.Unit, but not sure if there is a better/easier way to get the same done.
I want to convert between the same units, but different ratios. For example, hertz to kilohertz to megahertz.
From my understanding, I first must define units with my specific ratios:
typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<0> > >::type Hertz_unit;
typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<3> > >::type KilloHertz_unit;
typedef boost::units::make_scaled_unit<si::frequency, scale<10, static_rational<6> > >::type MegaHertz_unit;
Then create quantities that represent the units:
typedef boost::units::quantity<Hertz_unit , double> Hertz;
typedef boost::units::quantity<KilloHertz_unit, double> KilloHertz;
typedef boost::units::quantity<MegaHertz_unit , double> MegaHertz;
Finally some constants and literals:
BOOST_UNITS_STATIC_CONSTANT( Hz, Hertz_unit );
BOOST_UNITS_STATIC_CONSTANT(KHz, KilloHertz_unit);
BOOST_UNITS_STATIC_CONSTANT(MHz, MegaHertz_unit );
Hertz operator"" _Hz (long double val) { return Hertz (val * Hz); }
KilloHertz operator"" _KHz (long double val) { return KilloHertz(val * KHz); }
MegaHertz operator"" _MHz (long double val) { return MegaHertz (val * MHz); }
Now I can use the quantities:
Hertz freq_1 = (10 * Hz);
KilloHertz freq_2 = (10 * KHz);
MegaHertz freq_3 = (10 * MHz);
// OR
Hertz freq_4 = 10.0_Hz;
KilloHertz freq_5 = 10.0_KHz;
MegaHertz freq_6 = 10.0_MHz;
// Convert between units
Hertz freq_7 = static_cast<Hertz>(10 * KHz);
Is this how Boost.Unit should be used or am I missing something that might make it easier to use?
Are there not already defined units/quantities that I can use somewhere hidden in a header? Or should this be done for all my units that I use?
Do I need to know/remember that Kilo is `scale<10, static_rational<3>' or is this already defined and available?
Aucun commentaire:
Enregistrer un commentaire