一 简介
头文件<ratio>
template< std::intmax_t Num, std::intmax_t Denom = 1 >
class ratio; (since C++11)
1. std::ratio 支持编译期的有理数运算。
2. 当 Num 和 Denom 是编译期的std::intmax_t的常量时,该模板的每个实例都精确表示某个有限有理数。
3. 只要 Num 和 Denom 不同,即使化简后表示的有理数相同,两个std::ratio也不是相同的类型.
two
std::ratio
with differentNum
orDenom
are distinct types even if they represent the same rational number (after reduction).
4. std::ratio 的成员 type表示的是该std::ratio的最简类型(lowest terms)。例如 std::ratio<2, 4>::type是std::ratio<1, 2> 。
二 辅助函数
std::ratio有一些用于算术运算和逻辑运算的辅助函数。
1. 算术运算
ratio_add
ratio_subtract
ratio_multiply
ratio_divide
它们的返回类型还是std::ratio。
2. 逻辑运算
ratio_equal
ratio_not_equal
ratio_less
ratio_less_equal
ratio_greater
ratio_greater_equal
它们通过value返回 std::true_type 或 std::false_type。
三 例子
#include <iostream>
#include <type_traits> // is_same
#include <ratio>
int main() {
// 类型比较及type成员
std::cout << std::boolalpha << std::is_same<std::ratio<10,20>, std::ratio<100,200>>()
<< std::endl;
std::cout << typeid(std::ratio<10, 20>::type).name() << std::endl;
std::cout << typeid(std::ratio<100, 200>::type).name() << std::endl;
// 静态数据成员
std::cout << std::ratio<100, 200>::num << std::endl;
std::cout << std::ratio<100, 200>::den << std::endl;
// 算术运算
using r = std::ratio_add<std::ratio<10,20>, std::ratio<100,200>>;
std::cout << r::num << std::endl;
std::cout << r::den << std::endl;
// 逻辑运算
std::cout << std::ratio_equal<std::ratio<10,20>, std::ratio<100,200>>::value << std::endl;
std::cin.get();
return 0;
}
结果:
四 相关常量类型
为了方便使用,<ratio>中定义了一些常量类型,如下:
yocto std::ratio<1, 1000000000000000000000000>, if std::intmax_t can represent the denominator
zepto std::ratio<1, 1000000000000000000000>, if std::intmax_t can represent the denominator
atto std::ratio<1, 1000000000000000000>
femto std::ratio<1, 1000000000000000>
pico std::ratio<1, 1000000000000>
nano std::ratio<1, 1000000000>
micro std::ratio<1, 1000000>
milli std::ratio<1, 1000>
centi std::ratio<1, 100>
deci std::ratio<1, 10>
deca std::ratio<10, 1>
hecto std::ratio<100, 1>
kilo std::ratio<1000, 1>
mega std::ratio<1000000, 1>
giga std::ratio<1000000000, 1>
tera std::ratio<1000000000000, 1>
peta std::ratio<1000000000000000, 1>
exa std::ratio<1000000000000000000, 1>
zetta std::ratio<1000000000000000000000, 1>, if std::intmax_t can represent the numerator
yotta std::ratio<1000000000000000000000000, 1>, if std::intmax_t can represent the numerator
五 参考