Skip to content

Commit

Permalink
xo-ratio: refactor: rename ratio.to<> -> ratio.convert_to<>
Browse files Browse the repository at this point in the history
  • Loading branch information
Rconybea committed Apr 27, 2024
1 parent d949a2d commit 92477b7
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions include/xo/ratio/ratio.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,17 @@ namespace xo {
/** @brief promote value to ratio type **/
template <typename Ratio, typename FromType, bool FromRatioFlag = ratio_concept<FromType>>
struct promoter_type;

/** @brief convert value to different numeric (or ratio) representation **/
template <typename Ratio, typename ToType, bool ToRatioFlag = ratio_concept<ToType>>
struct converter_type;
}

/** @class ratio
* @brief represent a ratio of two Int values.
**/
template <typename Int> requires std::totally_ordered<Int>
template <typename Int>
requires std::totally_ordered<Int>
struct ratio
{
public:
Expand Down Expand Up @@ -255,7 +260,9 @@ namespace xo {
* For example: to int or double
**/
template <typename Repr>
constexpr Repr to() const noexcept { return num_ / static_cast<Repr>(den_); }
constexpr Repr convert_to() const noexcept {
return detail::converter_type<ratio, Repr>::convert(*this);
}

/** @brief convert to short human-friendly flatstring representation
*
Expand Down Expand Up @@ -361,6 +368,23 @@ namespace xo {
};
}

namespace detail {
template <typename Ratio, typename ToType, bool ToRatioFlag>
struct converter_type;

template <typename Ratio, typename ToType>
struct converter_type<Ratio, ToType, true /*ToRatioFlag*/> {
/* to convert to a ratio, can just use built-in conversion */
static constexpr ToType convert(Ratio x) { return ToType(x.num(), x.den()); }
};

template <typename Ratio, typename ToType>
struct converter_type<Ratio, ToType, false /*!ToRatioFlag*/> {
/* to convert to non-ratio, do division */
static constexpr ToType convert(Ratio x) { return x.num() / static_cast<ToType>(x.den()); }
};
}

/** @brief create a ratio in lowest terms from two integers **/
template <typename Int1, typename Int2>
constexpr auto
Expand Down

0 comments on commit 92477b7

Please sign in to comment.