A ratio is a C++ standard-library class template that represents a rational number through compile-time numerator and denominator values. It replaces repeated conversion constants with named, reusable units. section 4.2.1
Use ratios to make fractional and unit-based calculations explicit:
- Declare values such as std::ratio<3, 6>; the type reduces this to the equivalent ratio 1/2. section 4.2.1
- Compare ratios with ratio_equal and combine them with ratio_add; these operations occur at compile time. section 4.2.1
- Use predefined SI ratios such as std::nano instead of spelling out large denominators. section 4.2.1
- Let chrono::duration use a ratio as its Period, defining how many seconds each tick represents. section 4.2 section 4.5
Reducing and adding ratios
std::cout << std::ratio<3, 6>::num << '/' << std::ratio<3, 6>::den << '\n'; using fract = std::ratio_add<std::ratio<3, 6>, std::ratio<1, 2>>; std::cout << fract::num << '/' << fract::den << '\n'; Both results represent 1/2 and 1/1 respectively. section 4.2.1
template<std::intmax_t Num, std::intmax_t Denom = 1> class ratio;
Inspect the template declaration showing that numerator and denominator are non-type template parameters. section 4.2.1
