Millimeters in boost :: units

I want to use boost :: units for some SI metrics. However, our code mainly deals with millimeters and instead of using

quantity<length> value = 1*milli*meter; 

we would prefer something like

 quantity<length> value = 1*millimeter; 

However, I'm not sure how to define a "millimeter" (without using #define).

Secondly, what is the overhead of using prefix units?

Update: this needs to be run without C ++ 11 features (i.e. without UDL)

+7
source share
3 answers

I use the following approach:

 // your namespace name for units namespace outernamespace { namespace millimeter_system { typedef boost::units::scaled_base_unit<boost::units::si::meter_base_unit, boost::units::scale<10, boost::units::static_rational<-3>>> millimeter_base_unit; typedef boost::units::make_system<millimeter_base_unit>::type system; typedef boost::units::unit<boost::units::length_dimension, system> length; BOOST_UNITS_STATIC_CONSTANT(millimeter, length); BOOST_UNITS_STATIC_CONSTANT(millimeters, length); } typedef boost::units::quantity<millimeter_system::length> quantity_millimeter; using millimeter_system::millimeter; using millimeter_system::millimeters; } // demonstration of usage void foo() { using namespace outernamespace; using namespace boost::units; using namespace boost::units::si; quantity_millimeter mm = 5 * millimeter; quantity<boost::units::si::length> m = 0.004 * meter; if (mm < static_cast<quantity_millimeter>(m)) { std::cout << 'lt ' << std::endl; } else { std::cout << 'geq ' << std::endl; } } 
+4
source

C ++ 11 is the easiest solution. You could do

 static const auto millimeter = milli * meter; 

or

 auto operator"" _mm (long double val) -> decltype(val * milli * meter) { return val * milli * meter; } 

There should be no performance penalty if you do not convert to other prefixes. And even if you do, it must be careless.

If you do not want to use C ++ 11, you will need to find the appropriate type of expression milli * meter , although you could just replace auto with int and read the compiler message.

+11
source

If you have a C ++ 11 compiler, you can use Custom literals to define your units.

 double operator"" _millimeter ( double value ) { return value; } 

You can use it like this:

 double foo = 1000_millimeter; 
-2
source

All Articles