C++11 std::ratio

一 简介

头文件<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 different Num or Denomare 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

五  参考

std::ratio

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值