From 7ee68df175c7062fe597ddb2bf7a2c0db9422c13 Mon Sep 17 00:00:00 2001 From: Nick Thompson Date: Sat, 16 Dec 2023 10:53:16 -0800 Subject: [PATCH] Test that default constructed objects are zero In a generic context, we often need to compare arithmetic types to zero. However, mp-units types cannot be default constructed from (say) `double`, so we cann write (e.g.) ```cpp if (x < T(0)) { // ... } ``` Instead, we have to use ```cpp constexpr auto ZERO = T{}; if (x < ZERO) { // ... } ``` This begs the question: Do we have a guarantee that `ZERO==0.0`? Add a unit test that verifies this behavior. --- test/unit_test/static/math_test.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/unit_test/static/math_test.cpp b/test/unit_test/static/math_test.cpp index 84848c0250..fb86724db8 100644 --- a/test/unit_test/static/math_test.cpp +++ b/test/unit_test/static/math_test.cpp @@ -37,9 +37,14 @@ template { return is_same_v && v1 == v2 && (... && (v1 == vs)); } - +// Ensure that default constructed objects are zero: +using T = decltype(2.0 * s); +constexpr auto ZERO = T{}; +static_assert(ZERO + ZERO == ZERO); #if __cpp_lib_constexpr_cmath || MP_UNITS_COMP_GCC - +// What if ZERO is not = 0, but infinity? +// Then the test above still passes. So check that the value is finite: +static_assert(isfinite(ZERO)); static_assert(compare(fma(2.0 * s, 3.0 * Hz, 1.0 * one), 7.0 * one)); static_assert(compare(fma(2.0 * one, 3.0 * m, 1.0 * m), 7.0 * m)); static_assert(compare(fma(2.0 * m, 3.0 * one, 1.0 * m), 7.0 * m));