TDDD38 - Extra lecture The ratio header Eric Elfving

advertisement
TDDD38 - Extra lecture
The ratio header
Eric Elfving
Department of Computer and Information Science
Linköpings Universitet
1/7
Definition
A ratio expresses a proportion (such as 1:3, or
1000:1) as a set of two compile-time constants
(its numerator and its denominator). The type
itself is used to express the ratio (objects of
these types hold no value)
2/7
ratio<N,D> has two member constants declared: num
and din. These represent the unique lowest reduction
of the ratio N:D.
3/7
clang implementation
template <intmax_t _Num, intmax_t _Den = 1>
class ratio
{
static_assert(__static_abs<_Num>::value >= 0,
"ratio numerator is out of range");
static_assert(_Den != 0, "ratio divide by 0");
static_assert(__static_abs<_Den>::value > 0,
"ratio denominator is out of range");
static constexpr const intmax_t __na = __static_abs<_Num>::value;
static constexpr const intmax_t __da = __static_abs<_Den>::value;
static constexpr const intmax_t __s
=
__static_sign<_Num>::value * __static_sign<_Den>::value;
static constexpr const intmax_t __gcd = __static_gcd<__na, __da>::value;
public:
static constexpr const intmax_t num = __s * __na / __gcd;
static constexpr const intmax_t den = __da / __gcd;
typedef ratio<num, den> type;
};
4/7
clang implementation
comments
• __static_XXX are internal template classes with
static const member value.
template <intmax_t _Xp>
struct __static_abs
{
static const intmax_t value = _Xp < 0 ? -_Xp : _Xp;
};
5/7
clang implementation
comments
• The public members are static - not member data
but part of the class type
• All values (and internal functions) are constexpr -
everything is calculated at compile-time.
• Denumerator is always positive - the sign is stored
in numerator.
• Usage of type intmax_t - Integer type with the
maximum width supported by implementation.
6/7
There are some arithmetic and comparison classes that
can be used with ratio types (see 1 for all):
static_assert(ratio_equal<ratio_add<ratio<1,10>, ratio<1,5>>,
ratio<3,10>>::value,
"1/10 + 1/5 != 3/10");
1
http://www.cplusplus.com/reference/ratio/
7/7
Predefined types
There are types representing all SI prefixes predefined.
Some examples2 :
using milli = ratio<1,1000>;
using kilo = ratio<1000,1>;
2
All available here:
http://www.cplusplus.com/reference/ratio/ratio/
www.liu.se
Download