From cc5663002a0edccec8e396aa60239285659c398a Mon Sep 17 00:00:00 2001 From: Alex Wang Date: Sun, 26 Mar 2023 23:59:18 -0400 Subject: [PATCH] Restrict implicit dimensionless ctor to unscaled values Implicit conversions to/from built-in types appear to be a potential source of confusion for dimensionless units with a scaling factor (e.g., percent<>) [0]. Disallowing implicit conversions in those cases might be a not-terrible way to eliminate this potential for confusion without decreasing usability. The idea for limiting the implicit conversion to unscaled values was adapted from mpusz/units [1]. I'm not entirely confident this implementation is the best approach, but it's at least not obviously broken. [0]: https://github.com/nholthaus/units/issues/301 [1]: https://github.com/mpusz/units/issues/412#issuecomment-1416925554 --- include/units/core.h | 6 ++++-- unitTests/main.cpp | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/include/units/core.h b/include/units/core.h index 38953ef7..4f710097 100644 --- a/include/units/core.h +++ b/include/units/core.h @@ -2277,11 +2277,13 @@ namespace units /** * @brief constructor - * @details enable implicit conversions from T types ONLY for linear dimensionless units + * @details enable implicit conversions from T types ONLY for unscaled linear dimensionless units * @param[in] value value of the unit */ template Ty, concepts::dimensionless Cf = ConversionFactor> - inline constexpr unit(const Ty value) noexcept : linearized_value(NumericalScale::linearize(static_cast(value))) + inline explicit(!std::ratio_equal_v::conversion_ratio, std::ratio<1>>) constexpr unit( + const Ty value) noexcept + : linearized_value(NumericalScale::linearize(static_cast(value))) { } diff --git a/unitTests/main.cpp b/unitTests/main.cpp index 373d2c0c..d49dcac1 100644 --- a/unitTests/main.cpp +++ b/unitTests/main.cpp @@ -3055,10 +3055,10 @@ TEST(Consistency, recovers_input_values) TEST(Consistency, percent) { percent a(50); - percent b = 50; + // percent b = 50; EXPECT_DOUBLE_EQ(a, 50_pct); - EXPECT_DOUBLE_EQ(b, 50_pct); + // EXPECT_DOUBLE_EQ(b, 50_pct); } TEST_F(UnitType, identity)