std::ratio_add
来自 cppreference.cn
定义于头文件 <ratio> |
||
template< class R1, class R2 > using ratio_add = /* see below */; |
(since C++11) | |
别名模板 std::ratio_add
表示将两个精确的有理分数相加的结果,这两个有理分数由 std::ratio 特化 R1
和 R2
表示。
结果是一个 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。
[edit] 注解
如果 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> 是相同的类型。
[edit] 示例
运行此代码
#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
[edit] 参见
(C++11) |
在编译时减去两个 ratio 对象(alias template) |