Skip to content
DryPerspective edited this page Sep 19, 2023 · 5 revisions

A recreation of the \<ratio\> header, which allows compile-time rational arithmetic and comes with ratio prefixes for SI ratios. Ratio objects with different numerators and denominators are equal if the fraction they represent is equal, e.g. dp::ratio<1,2> is considered equal to dp::ratio<3,6>. Ratio calculations are performed at compile time and without overflow.

Note that while the arithmetic metafunctions (ratio_add, ratio_subtract, etc) are provided through templated using aliases in C++11, this is not possible in C++98. Here they are represented as structs whose members match the interface of the standard approach.

Note that this header includes static_assert.h

Types and Metafunctions

ratio Base ratio class. Denominator cannot be zero
ratio_add Metafunction representing the sum of two ratios
ratio_subtract Metafunction representing the difference of two ratios
ratio_multiply Metafunction representing the product of two ratios
ratio_divide Metafunction representing the quotient of two ratios
ratio_equal Metafunction to compare two ratios for equality
ratio_not_equal Metafunction to compare two ratios for inequality
ratio_less Metafunction to determine if one ratio is less than another
ratio_less_equal Metafunction to determine if one ratio is less than or equal to another
ratio_greater Metafunction to determine if one ratio is greater than another
ratio_greater_equal Metafunction to determine if one ratio is greater than or equal to another

Sample Code

#include "cpp98/ratio.h"

int main(){
    typedef dp::ratio<56,81> initialFraction;
    typedef dp::ratio<45/89> secondFraction;
    typedef typename dp::ratio_add<initialFraction, secondFraction>::type sum;
    typedef typename dp::ratio_multiply<initialFraction,initialFraction>::type initialSquared;
    typedef typename dp::ratio_less<sum,initialSquared> result;

    static const bool IsLess = result::value;   //This bool now contains the value of (56/81 + 45/89) < (56/81)^2 as calculated entirely at compile time
}

Clone this wiki locally