std::ratio_add

From cppreference.com
< cpp‎ | numeric‎ | ratio
 
 
Metaprogramming library
Type traits
Type categories
(C++11)
(C++14)  
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Type properties
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(until C++20*)
(C++11)(deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
(C++11)(C++11)(C++11)
Type transformations
(C++11)(deprecated in C++23)
(C++11)(deprecated in C++23)
(C++11)
(C++11)
(C++17)

(C++11)(until C++20*)(C++17)
Compile-time rational arithmetic
Compile-time integer sequences
 
Compile time rational arithmetic
(C++11)
Arithmetic
ratio_add
(C++11)
Comparison
(C++11)
 
Defined in header <ratio>
template< class R1, class R2 >
using ratio_add = /* see below */;
(since C++11)

The alias template std::ratio_add denotes the result of adding two exact rational fractions represented by the std::ratio specializations R1 and R2.

The result is a std::ratio specialization std::ratio<U, V>, such that given Num == R1::num * R2::den + R2::num * R1::den and Denom == R1::den * R2::den (computed without arithmetic overflow), U is std::ratio<Num, Denom>::num and V is std::ratio<Num, Denom>::den.

Notes

If U or V is not representable in std::intmax_t, the program is ill-formed. If Num or Denom is not representable in std::intmax_t, the program is ill-formed unless the implementation yields correct values for U and V.

The above definition requires that the result of std::ratio_add<R1, R2> be already reduced to lowest terms; for example, std::ratio_add<std::ratio<1, 3>, std::ratio<1, 6>> is the same type as std::ratio<1, 2>.

Example

#include <iostream>
#include <ratio>
 
int main()
{
    using two_third = std::ratio<2, 3>;
    using one_sixth = std::ratio<1, 6>;
    using sum = std::ratio_add<two_third, one_sixth>;
 
    std::cout << "2/3 + 1/6 = " << sum::num << '/' << sum::den << '\n';
}

Output:

2/3 + 1/6 = 5/6

See also

subtracts two ratio objects at compile-time
(alias template)