Skip to content

Commit

Permalink
Test that default constructed objects are zero
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
NAThompson committed Dec 16, 2023
1 parent 84e6a6d commit 7ee68df
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions test/unit_test/static/math_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,14 @@ template<typename T1, typename T2, typename... Ts>
{
return is_same_v<T1, T2> && 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));
Expand Down

0 comments on commit 7ee68df

Please sign in to comment.