From c75eb02ea7da8900167438061c8afb5cbb12ef66 Mon Sep 17 00:00:00 2001 From: Chip Hogg Date: Wed, 29 Dec 2021 21:10:29 -0500 Subject: [PATCH] Finish fleshing out make_ratio --- src/core/include/units/magnitude.h | 12 ++++-- test/unit_test/runtime/magnitude_test.cpp | 45 +++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/src/core/include/units/magnitude.h b/src/core/include/units/magnitude.h index 5c7963a2..d411766a 100644 --- a/src/core/include/units/magnitude.h +++ b/src/core/include/units/magnitude.h @@ -81,7 +81,7 @@ using prime_factorization_t = typename prime_factorization::type; } // namespace detail template -auto make_ratio() { +constexpr auto make_ratio() { return quotient_t, detail::prime_factorization_t>{}; } @@ -95,10 +95,14 @@ struct pi { template struct magnitude { - bool operator==(magnitude) const { return true; } + template + constexpr bool operator==(M) const { return std::is_same_v; } - template - bool operator==(magnitude) const { return false; } + template + constexpr friend auto operator*(magnitude, M) { return product_t{}; } + + template + constexpr friend auto operator/(magnitude, M) { return quotient_t{}; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/test/unit_test/runtime/magnitude_test.cpp b/test/unit_test/runtime/magnitude_test.cpp index d0a51b1c..e0f5a00f 100644 --- a/test/unit_test/runtime/magnitude_test.cpp +++ b/test/unit_test/runtime/magnitude_test.cpp @@ -248,6 +248,51 @@ TEST_CASE("Equality works for magnitudes") CHECK(make_ratio<3>() != make_ratio<5>()); CHECK(make_ratio<3>() != make_ratio<3, 2>()); } + + SECTION("Supports constexpr") + { + constexpr auto eq = make_ratio<4, 5>() == make_ratio<4, 3>(); + CHECK(!eq); + } +} + +TEST_CASE("Multiplication works for magnitudes") +{ + SECTION("Reciprocals reduce to null magnitude") + { + CHECK(make_ratio<3, 4>() * make_ratio<4, 3>() == make_ratio<1>()); + } + + SECTION("Products work as expected") + { + CHECK(make_ratio<4, 5>() * make_ratio<4, 3>() == make_ratio<16, 15>()); + } + + SECTION("Supports constexpr") + { + constexpr auto p = make_ratio<4, 5>() * make_ratio<4, 3>(); + CHECK(p == make_ratio<16, 15>()); + } +} + +TEST_CASE("Division works for magnitudes") +{ + SECTION("Dividing anything by itself reduces to null magnitude") + { + CHECK(make_ratio<3, 4>() / make_ratio<3, 4>() == make_ratio<1>()); + CHECK(make_ratio<15>() / make_ratio<15>() == make_ratio<1>()); + } + + SECTION("Quotients work as expected") + { + CHECK(make_ratio<4, 5>() / make_ratio<4, 3>() == make_ratio<3, 5>()); + } + + SECTION("Supports constexpr") + { + constexpr auto q = make_ratio<4, 5>() / make_ratio<4, 3>(); + CHECK(q == make_ratio<3, 5>()); + } } namespace detail