From 3353f492aded11d0b20ce4b40bcd7cf609a8b361 Mon Sep 17 00:00:00 2001 From: Mateusz Pusz Date: Thu, 6 Jun 2024 20:59:41 +0200 Subject: [PATCH] refactor: unit comparison functions optimized for the case of the same unit type --- src/core/include/mp-units/framework/unit.h | 32 ++++++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/core/include/mp-units/framework/unit.h b/src/core/include/mp-units/framework/unit.h index 3299db0b..c362afa1 100644 --- a/src/core/include/mp-units/framework/unit.h +++ b/src/core/include/mp-units/framework/unit.h @@ -500,11 +500,16 @@ MP_UNITS_EXPORT_END namespace detail { -[[nodiscard]] consteval auto have_same_canonical_reference_unit(Unit auto u1, Unit auto u2) +template +[[nodiscard]] consteval auto have_same_canonical_reference_unit(U1 u1, U2 u2) { - using canonical_lhs = decltype(get_canonical_unit(u1)); - using canonical_rhs = decltype(get_canonical_unit(u2)); - return std::is_same{}; + if constexpr (is_same_v) + return std::true_type{}; + else { + using canonical_lhs = decltype(get_canonical_unit(u1)); + using canonical_rhs = decltype(get_canonical_unit(u2)); + return std::is_same{}; + } } } // namespace detail @@ -513,8 +518,11 @@ namespace detail { MP_UNITS_EXPORT template [[nodiscard]] consteval bool operator==(U1 lhs, U2 rhs) { - return decltype(detail::have_same_canonical_reference_unit(lhs, rhs))::value && - decltype(get_canonical_unit(lhs))::mag == decltype(get_canonical_unit(rhs))::mag; + if constexpr (is_same_v) + return true; + else + return decltype(detail::have_same_canonical_reference_unit(lhs, rhs))::value && + decltype(get_canonical_unit(lhs))::mag == decltype(get_canonical_unit(rhs))::mag; } namespace detail { @@ -603,9 +611,13 @@ inline constexpr auto ppm = parts_per_million; // convertible_to -[[nodiscard]] consteval bool convertible(Unit auto from, Unit auto to) +template +[[nodiscard]] consteval bool convertible(U1 from, U2 to) { - return decltype(detail::have_same_canonical_reference_unit(from, to))::value; + if constexpr (is_same_v) + return true; + else + return decltype(detail::have_same_canonical_reference_unit(from, to))::value; } // Common unit @@ -615,7 +627,9 @@ template [[nodiscard]] consteval Unit auto common_unit(U1 u1, U2 u2) requires(decltype(detail::have_same_canonical_reference_unit(u1, u2))::value) { - if constexpr (U1{} == U2{}) { + if constexpr (is_same_v) + return u1; + else if constexpr (U1{} == U2{}) { if constexpr (std::derived_from) return u1; else if constexpr (std::derived_from)