Rounding policies for potentially lossy value conversions
Synopsis
Declared in <mp‐units/framework/rounding.h>
struct truncated_t;
Description
A conversion without a policy (e.g. q.in(u)) is only available when the framework considers it value‐preserving (following the std::chrono convention, a floating‐point destination is always considered such). For the conversions considered truncating (e.g. an integral representation scaled by a non‐integral factor, or a narrowing of the representation type), the user has to explicitly state what should happen to the information that does not fit by passing a rounding policy as the last function argument:
{.cpp}
quantity q1 = (1234 * m).in(km, truncated); // 1 km
quantity q2 = (1567 * m).in(km, rounded); // 2 km
quantity q3 = (-1500 * m).in(km, rounded_down); // -2 km
quantity q4 = (1.23 * s).in<int>(ms, rounded_up); // 1231 ms
The policy specifies how to round the exact conversion result to a value representable in the destination type:
-
truncated‐ the semantics ofstatic_castandstd::chrono::duration_cast: rounds towards zero for an integral destination; a floating‐point destination converts to the nearest representable value, -
rounded‐ rounds to the nearest representable value, to even in halfway cases (the semantics ofstd::chrono::round), -
rounded_down‐ rounds towards negative infinity (the semantics ofstd::chrono::floor), -
rounded_up‐ rounds towards positive infinity (the semantics ofstd::chrono::ceil).
A floating‐point destination represents every conversion result with a rounding error of at most half ULP (rounded semantics), and the directed modes cannot be delivered for it, which is why it accepts only the truncated and rounded policies.
Note that mp_units::floor/ceil/round<U>(q) perform a different operation: they round to an integral multiple of the target unit even when the representation could store the exact result (e.g. for a floating‐point representation). The policies never adjust a value that the destination represents exactly. Both coincide for integral representations.
Member Functions
Name |
Description |
|
Default constructor |
Created with MrDocs