命名空间
Variants
Actions

std::ratio_add

来自 cppreference.cn
< cpp‎ | numeric‎ | ratio
 
 
元编程库
类型特征
类型类别
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
类型属性
(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)
类型特征常量
元函数
(C++17)
支持的操作
关系和属性查询
类型修改
(C++11)(C++11)(C++11)
类型转换
(C++11)(deprecated in C++23)
(C++11)(deprecated in C++23)
(C++11)
(C++11)(until C++20*)(C++17)

(C++11)
(C++17)
编译时有理算术
编译时整数序列
 
编译时有理算术
(C++11)
算术
ratio_add
(C++11)
比较
(C++11)
 
定义于头文件 <ratio>
template< class R1, class R2 >
using ratio_add = /* see below */;
(since C++11)

别名模板 std::ratio_add 表示将两个精确的有理分数相加的结果,这两个有理分数由 std::ratio 特化 R1R2 表示。

结果是一个 std::ratio 特化 std::ratio<U, V>,其中给定 Num == R1::num * R2::den + R2::num * R1::denDenom == R1::den * R2::den (在没有算术溢出的情况下计算),Ustd::ratio<Num, Denom>::numVstd::ratio<Num, Denom>::den

[edit] 注解

如果 UV 无法用 std::intmax_t 表示,则程序是非良构的。如果 NumDenom 无法用 std::intmax_t 表示,除非实现为 UV 产生正确的值,否则程序是非良构的。

上述定义要求 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] 参见

在编译时减去两个 ratio 对象
(alias template)[edit]