Skip to content

mp_units::UnitMagnitude

A concept matching every unit magnitude

Synopsis

Declared in <mp-units/framework/unit_magnitude_concepts.h>

template<typename T>
concept UnitMagnitude =
  is_specialization_of_v<std::remove_const_t<T>, detail::unit_magnitude>;

Description

A unit magnitude is the exact factor between a unit and the unit it is defined from, created by mag, mag_ratio, mag_power, and their products, as in mag<1000> * si::metre. Its type is an implementation detail, so this concept is the only public way to name one. A representation type needs that when it scales itself, through an operator*(T, M) that may return a different type, as one tracking its own precision does.

// the power of ten at or below a magnitude
template<UnitMagnitude auto M>
consteval int decimal_shift();

// a decimal fixed-point number, `count` units of 10 to the power of `Exp`
template<int Exp>
struct decimal {
  std::int64_t count;

  // ... the arithmetic and comparison operators of a representation type ...

  // called by the library during a unit conversion, with the conversion factor: its power of
  // ten moves the decimal point into the type, and only the rest rescales the count
  template<UnitMagnitude M>
  friend constexpr auto operator*(decimal value, M)
  {
    constexpr int shift = decimal_shift<M{}>();
    return decimal<Exp + shift>{
      scale_by_magnitude<std::int64_t>(M{} / mag_power<10, shift>, value.count)};
  }
};

// the type rescales its own precision, so a conversion may be implicit
template<Unit auto From, int Exp, Unit auto To>
constexpr bool mp_units::implicitly_scalable<From, decimal<Exp>, To, decimal<Exp>> = true;

quantity<si::metre, decimal<0>> track_length{decimal<0>{1500}, si::metre};
quantity in_kilometres = track_length.in(km);          // decimal<-3>{1500}, exactly 1.5 km
quantity in_feet = track_length.in(yard_pound::foot);  // decimal<0>{4921}
// values of types nobody spells, so naming what each one is helps where `auto` alone doesn't
constexpr UnitMagnitude auto milli_factor = mag_ratio<1, 1000>;
constexpr Unit auto thousandth_of_metre = milli_factor * si::metre;

See Also