liveBook · Manning

Ratio

As explained in Learn C++ by Example

A ratio is a C++ standard library class template representing a rational number with compile-time numerator and denominator values.

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

How Learn C++ by Example covers it

How deep it goes
Defines template parameters, normalization, comparison, arithmetic, and duration integration, without detailing implementation internals.
Examples
Demonstrates ratio reduction, equality testing, addition, nanosecond representation, and duration periods.
What you can do after
Apply it via std::ratio and chrono::duration to express units and perform checked compile-time fraction arithmetic.
How it connects
Connects rational numbers with duration, chrono, ratio_equal, ratio_add, and SI units.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.