Skip to content

Commit

Permalink
Explicitly casting ratio to target type on unit cast
Browse files Browse the repository at this point in the history
  • Loading branch information
bernedom committed Nov 23, 2022
1 parent fadcffb commit ea979be
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
12 changes: 11 additions & 1 deletion include/SI/detail/unit_cast.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

#include "detail.h"
#include <ratio>
#include <type_traits>

namespace SI::detail {

Expand All @@ -28,11 +29,20 @@ constexpr auto unit_cast(const _rhs_T &rhs) {
typename _rhs_T::internal_type, typename _rhs_T::ratio>,
_rhs_T>::value,
"is of type unit_t or a derived class");

using conversion_ratio =
std::ratio_divide<typename _rhs_T::ratio, typename _target_type::ratio>;
static_assert(std::is_convertible<decltype(conversion_ratio::den),
typename _rhs_T::internal_type>::value,
"conversion ratio denominator is convertible to internal type");

// the static cast is needed because MSVC will print a warning without it
// because of a possible loss of precision when rhs is of type double
return _target_type(
((rhs.value() * conversion_ratio::num) / conversion_ratio::den));
((rhs.value() * static_cast<typename _target_type::internal_type>(
conversion_ratio::num)) /
static_cast<typename _target_type::internal_type>(
conversion_ratio::den)));
}

template <typename _unit_lhs, typename _unit_rhs>
Expand Down
1 change: 1 addition & 0 deletions test/src/detail_tests/unit_t_conversions_tests.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <SI/detail/unit.h>

#include <cstdint>
#include <iostream>
#include <type_traits>

using namespace SI::detail;
Expand Down

0 comments on commit ea979be

Please sign in to comment.