Professional C__ - Marc Gregoire [277]
typedef ratio<1, 60> r1;
The numerator and denominator of the r1 rational number are compile time constants and can be accessed as follows:
intmax_t num = r1::num;
intmax_t den = r1::den;
Remember that a ratio is a compile time constant, which means that the numerator and denominator need to be known at compile time. The following will generate a compiler error:
intmax_t n = 1;
intmax_t d = 60;
typedef ratio Making n and d constants removes the compilation error: const intmax_t n = 1; const intmax_t d = 60; typedef ratio Rational numbers are always normalized. For a rational number ratio num = sign(n)*sign(d)*abs(n)/gcd den = abs(d)/gcd The library supports adding, subtracting, multiplying, and dividing rational numbers. Because all these operations are also happening at compile time, you cannot use the standard arithmetic operators. Instead, you need to use specific templates in combination with typedefs. The following arithmetic ratio templates are available: ratio_add, ratio_subtract, ratio_multiply, and ratio_divide. These templates calculate the result as a new ratio type. This type can be accessed with the embedded typedef called type. For example, the following code first defines two ratios, one representing 1/60 and the other representing 1/30. The ratio_add template adds those two rational numbers together to produce the result rational number, which, after normalization, will be 1/20: typedef ratio<1, 60> r1; typedef ratio<1, 30> r2; typedef ratio_add The standard also defines a number of ratio comparison templates: ratio_equal, ratio_not_equal, ratio_less, ratio_less_equal, ratio_greater, and ratio_greater_equal. Just like the arithmetic ratio templates, the ratio comparison templates are all evaluated at compile time. These comparison templates create a new type, std::integral_constant, representing the result. An integral_constant is a struct template that stores a type and a compile time constant value. For example, integral_constant typedef ratio<1, 60> r1; typedef ratio<1, 30> r2; typedef ratio_less cout << boolalpha << res::value << endl; The following example combines everything. Note that since ratios are compile time constants, you cannot do something like cout << r1, you need to get the numerator and denominator and print them separately: // Define a compile time rational number typedef ratio<1, 60> r1; cout << "1) " << r1::num << "/" << r1::den << endl; // Get numerator and denominator intmax_t num = r1::num; intmax_t den = r1::den; cout << "2) " << num << "/" << den << endl; // Add two rational numbers typedef ratio<1, 30> r2; cout << "3) " << r2::num << "/" << r2::den << endl; typedef ratio_add cout << "4) " << result::num << "/" << result::den << endl; // Compare two rational numbers typedef ratio_less cout << "5) " << boolalpha << res::value << endl;