C++11之std::ratio

今天在写代码,遇到了需要将std::chrono::duration转换到timespec,需要得到秒和纳秒,于是乎,我想到用std::nano::den(std::ratio<1, 1000000000>的别名)来做为纳秒求余的分母。

std::ratio的定义在<ratio>,核心代码如下:

  /**
   *  @brief Provides compile-time rational arithmetic.
   *
   *  This class template represents any finite rational number with a
   *  numerator and denominator representable by compile-time constants of
   *  type intmax_t. The ratio is simplified when instantiated.
   *
   *  For example:
   *  @code
   *    std::ratio<7,-21>::num == -1;
   *    std::ratio<7,-21>::den == 3;
   *  @endcode
   *
  */
  template<intmax_t _Num, intmax_t _Den = 1>
    struct ratio
    {
      static_assert(_Den != 0, "denominator cannot be zero");
      static_assert(_Num >= -__INTMAX_MAX__ && _Den >= -__INTMAX_MAX__,
            "out of range");

      // Note: sign(N) * abs(N) == N
      static constexpr intmax_t num =
        _Num * __static_sign<_Den>::value / __static_gcd<_Num, _Den>::value;

      static constexpr intmax_t den =
        __static_abs<_Den>::value / __static_gcd<_Num, _Den>::value;

      typedef ratio<num, den> type;
    };

第一个参数_Num代表了分子,第二个参数 _Den代表了分母。
num是约分后的分子,den是约分后的分母。numnumerator的缩写,表示分子。dendenominator的缩写,表示分母。

示例代码:

// ratio example
#include <iostream>
#include <ratio>

int main ()
{
  typedef std::ratio<1,3> one_third;
  typedef std::ratio<2,4> two_fourths;

  std::cout << "one_third= " << one_third::num << "/" << one_third::den << std::endl;
  std::cout << "two_fourths= " << two_fourths::num << "/" << two_fourths::den << std::endl;

  typedef std::ratio_add<one_third,two_fourths> sum;

  std::cout << "sum= " << sum::num << "/" << sum::den;
  std::cout << " (which is: " << ( double(sum::num) / sum::den ) << ")" << std::endl;

  std::cout << "1 kilogram has " << ( std::kilo::num / std::kilo::den ) << " grams";
  std::cout << std::endl;

  return 0;
}

运行结果:

one_third= 1/3
two_fourths= 1/2
sum= 5/6 (which is 0.833333)
1 kilogram has 1000 grams

reference:

http://www.cplusplus.com/reference/ratio/ratio/

https://zh.cppreference.com/w/cpp/types/aligned_storage

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EnjoyCodingAndGame

愿我的知识,成为您的财富!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值