5 Quantities and units library [quantities]
5.9 std::chrono interoperability [qty.chrono]
namespace mp_units {
template<typename Period>
consteval auto time-unit-from-chrono-period()
{
using namespace si;
if constexpr (is_same_v<Period, std::chrono::nanoseconds::period>)
return nano<second>;
else if constexpr (is_same_v<Period, std::chrono::microseconds::period>)
return micro<second>;
else if constexpr (is_same_v<Period, std::chrono::milliseconds::period>)
return milli<second>;
else if constexpr (is_same_v<Period, std::chrono::seconds::period>)
return second;
else if constexpr (is_same_v<Period, std::chrono::minutes::period>)
return minute;
else if constexpr (is_same_v<Period, std::chrono::hours::period>)
return hour;
else if constexpr (is_same_v<Period, std::chrono::days::period>)
return day;
else if constexpr (is_same_v<Period, std::chrono::weeks::period>)
return mag<7> * day;
else
return mag_ratio<Period::num, Period::den> * second;
}
template<typename Rep, typename Period>
struct quantity_like_traits<std::chrono::duration<Rep, Period>> {
static constexpr auto reference = time-unit-from-chrono-period<Period>();
static constexpr bool explicit_import = false;
static constexpr bool explicit_export = false;
using rep = Rep;
using T = std::chrono::duration<Rep, Period>;
static constexpr rep to_numerical_value(const T& q) noexcept(
std::is_nothrow_copy_constructible_v<rep>)
{
return q.count();
}
static constexpr T from_numerical_value(const rep& v) noexcept(
std::is_nothrow_copy_constructible_v<rep>)
{
return T(v);
}
};
template<typename Clock>
struct chrono_point_origin_ final : absolute_point_origin<isq::time> {
using clock = Clock;
};
template<typename Clock, typename Rep, typename Period>
struct quantity_point_like_traits<
std::chrono::time_point<Clock, std::chrono::duration<Rep, Period>>> {
static constexpr auto reference = time-unit-from-chrono-period<Period>();
static constexpr auto point_origin = chrono_point_origin<Clock>;
static constexpr bool explicit_import = false;
static constexpr bool explicit_export = false;
using rep = Rep;
using T = std::chrono::time_point<Clock, std::chrono::duration<Rep, Period>>;
static constexpr rep to_numerical_value(const T& tp) noexcept(
std::is_nothrow_copy_constructible_v<rep>)
{
return tp.time_since_epoch().count();
}
static constexpr T from_numerical_value(const rep& v) noexcept(
std::is_nothrow_copy_constructible_v<rep>)
{
return T(std::chrono::duration<Rep, Period>(v));
}
};
}