Namespaces
Variants

std:: ratio_multiply

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_multiply = /* 见下文 */ ;
(C++11 起)

别名模板 std::ratio_multiply 表示两个由 std::ratio 特化 R1 R2 所表示的精确有理分数相乘的结果。

结果是 std::ratio 的特化 std:: ratio < U, V > ,其中给定 Num == R1 :: num * R2 :: num 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_multiply < R1, R2 > 的结果必须已约简至最简形式;例如, std :: ratio_multiply < std:: ratio < 1 , 6 > , std:: ratio < 4 , 5 >> std:: ratio < 2 , 15 > 属于同一类型。

示例

#include <iostream>
#include <ratio>
int main()
{
    using two_third = std::ratio<2, 3>;
    using one_sixth = std::ratio<1, 6>;
    using product = std::ratio_multiply<two_third, one_sixth>;
    static_assert(std::ratio_equal_v<product, std::ratio<13, 117>>);
    std::cout << "2/3 * 1/6 = " << product::num << '/' << product::den << '\n';
}

输出:

2/3 * 1/6 = 1/9

参见

在编译时除法两个 ratio 对象
(别名模板)