Finish fleshing out make_ratio

This commit is contained in:
Chip Hogg
2021-12-29 21:10:29 -05:00
parent 8a1ed3adcb
commit c75eb02ea7
2 changed files with 53 additions and 4 deletions

View File

@@ -81,7 +81,7 @@ using prime_factorization_t = typename prime_factorization<N>::type;
} // namespace detail
template <std::intmax_t N, std::intmax_t D = 1>
auto make_ratio() {
constexpr auto make_ratio() {
return quotient_t<detail::prime_factorization_t<N>, detail::prime_factorization_t<D>>{};
}
@@ -95,10 +95,14 @@ struct pi {
template <BasePower... Bs>
struct magnitude {
bool operator==(magnitude) const { return true; }
template <Magnitude M>
constexpr bool operator==(M) const { return std::is_same_v<magnitude, M>; }
template <BasePower... OtherBs>
bool operator==(magnitude<OtherBs...>) const { return false; }
template <Magnitude M>
constexpr friend auto operator*(magnitude, M) { return product_t<magnitude, M>{}; }
template <Magnitude M>
constexpr friend auto operator/(magnitude, M) { return quotient_t<magnitude, M>{}; }
};
////////////////////////////////////////////////////////////////////////////////////////////////////

View File

@@ -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