C++11之std::ratio

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

std::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
    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 type;
    };

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

C++11之std::ratio_第1张图片

C++11之std::ratio_第2张图片

示例代码:

// ratio example
#include 
#include 

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 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

你可能感兴趣的:(C++11之std::ratio)