|
Unit Conversion and Dimensional Analysis Library 3.6.1
A compile-time, header-only C++23 dimensional-analysis library
|
Time quantities convert implicitly to and from std::chrono::duration in both directions.
A units time quantity and a std::chrono::duration model the same thing, and they interconvert: assign a std::chrono::duration to a time quantity, or a time quantity to a std::chrono::duration, and the value converts. This is enabled only for time units, so no other dimension can be silently mistaken for a duration.
Related how-to guides: defining new units, math functions, JSON serialization.
The chrono-to-units direction converts the duration's Rep/Period into the target unit; assigning std::chrono::seconds{90} to a minutes<double> gives 1.5. The units-to-chrono direction reads the quantity's value into the duration's representation.
Because the chrono-to-units conversion is implicit, a std::chrono::duration participates anywhere a time quantity is expected — including as an operand you first bind to a time quantity, and as a function argument. Once both operands are time quantities, the arithmetic deduces its result unit as usual:
A function that takes a time quantity accepts a std::chrono::duration directly, since the conversion happens at the call boundary:
Caveat: the built-in arithmetic operators require both operands to be units quantities. A raw std::chrono::duration on one side of + (for example 1.5_min + std::chrono::seconds{30}) does not compile, because the operator's constraints reject a non-units operand rather than triggering the conversion mid-overload resolution. Convert the chrono value to a time quantity first — assign it to a named variable, or pass it where a quantity is expected — as shown above.
Note: std::common_type is specialized for the unnamed unit<...> time form and a std::chrono::duration, so generic code that computes a common type over the base unit form is supported. A named time type such as minutes<double> does not itself match that specialization; prefer an explicit conversion in mixed expressions.
A class template argument deduction guide constructs a time quantity directly from a std::chrono::duration, deducing the unit from the duration's period:
The deduced unit carries the duration's period, so q.value() reports 250 (milliseconds), not 0.25 (seconds). Assign to a named time type when you want the value in a specific unit.