CNL  2.0.2 (development)
Compositional Numeric Library
definition.h
1 
2 // Copyright John McFarlane 2015 - 2018.
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file ../LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
6 
7 #if !defined(CNL_IMPL_FRACTION_DEFINITION_H)
8 #define CNL_IMPL_FRACTION_DEFINITION_H
9 
10 #include "../../fixed_point.h"
11 #include "../../integer.h"
12 #include "../num_traits/set_width.h"
13 #include "../ssizeof.h"
14 
15 #include <concepts>
16 #include <limits>
17 #include <type_traits>
18 
20 namespace cnl {
21 
26 
27  template<fixed_point Numerator = int, fixed_point Denominator = Numerator>
28  struct fraction {
29  static_assert(
31  "ill-formed if only one template parameter is floating-point");
32 
34  using numerator_type = Numerator;
35 
37  using denominator_type = Denominator;
38 
39  explicit constexpr fraction(Numerator n, Denominator d);
40 
41  template<integer Integer>
42  explicit constexpr fraction(Integer const& i);
43 
44  template<fixed_point RhsNumerator, fixed_point RhsDenominator>
45  // NOLINTNEXTLINE(hicpp-explicit-conversions, google-explicit-constructor)
47 
48  template<std::floating_point FloatingPoint>
49  explicit constexpr fraction(FloatingPoint);
50 
52  template<std::floating_point Scalar>
53  [[nodiscard]] explicit constexpr operator Scalar() const
54  {
55  return static_cast<Scalar>(numerator) / static_cast<Scalar>(denominator);
56  }
57 
59  numerator_type numerator; // NOLINT(misc-non-private-member-variables-in-classes)
60 
62  denominator_type denominator = 1; // NOLINT(misc-non-private-member-variables-in-classes)
63  };
64 
65  fraction(float)->fraction<_impl::set_width_t<int, _impl::ssizeof<float>() * CHAR_BIT>>;
66 
67  fraction(double)->fraction<_impl::set_width_t<int, _impl::ssizeof<double>() * CHAR_BIT>>;
68 
69 #if defined(CNL_INT128_ENABLED)
70  fraction(long double)->fraction<_impl::set_width_t<int, _impl::ssizeof<long double>() * CHAR_BIT>>;
71 #endif
72 
73  template<integer Integer>
74  fraction(Integer) -> fraction<Integer>;
75 }
76 
77 #endif // CNL_IMPL_FRACTION_DEFINITION_H
cnl::fraction
numeric type represented as the fraction, numerator / denominator
Definition: definition.h:28
cnl::fraction::denominator
denominator_type denominator
the denominator (bottom number) of the fraction
Definition: definition.h:62
cnl::fraction::numerator_type
Numerator numerator_type
alias to Numerator
Definition: definition.h:34
cnl::fraction::numerator
numerator_type numerator
the numerator (top number) of the fraction
Definition: definition.h:59
cnl
compositional numeric library
Definition: abort.h:15
cnl::fraction::denominator_type
Denominator denominator_type
alias to Denominator
Definition: definition.h:37
std::numeric_limits