Namespaces
Variants

std:: ratio_add

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(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
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
ヘッダーで定義 <ratio>
template < class R1, class R2 >
using ratio_add = /* see below */ ;
(C++11以降)

エイリアステンプレート std::ratio_add は、 std::ratio 特殊化 R1 および R2 によって表される2つの正確な有理分数を加算した結果を表します。

結果は std::ratio の特殊化 std:: ratio < U, V > であり、与えられた Num == R1 :: num * R2 :: den + R2 :: num * R1 :: den および Denom == R1 :: den * R2 :: den (算術オーバーフローなしで計算)に対して、 U std:: ratio < Num, Denom > :: num であり、 V std:: ratio < Num, Denom > :: den である。

注記

U または V std::intmax_t で表現できない場合、プログラムは不適格です。 Num または Denom std::intmax_t で表現できない場合、実装が U V に対して正しい値を生成するのでなければ、プログラムは不適格です。

上記の定義では、 std :: ratio_add < R1, R2 > の結果が既に既約分数であることを要求しています。例えば、 std :: ratio_add < std:: ratio < 1 , 3 > , std:: ratio < 1 , 6 >> std:: ratio < 1 , 2 > と同じ型となります。

#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';
}

出力:

2/3 + 1/6 = 5/6

関連項目

コンパイル時に2つの ratio オブジェクトを減算する
(エイリアステンプレート)