std::chrono::time_point_cast

template <class ToDuration, class Clock, class Duration>

time_point<Clock, ToDuration> time_point_cast(

                                 const time_point<Clock, Duration> &t);
(C++11 起)
(C++14 前)
template <class ToDuration, class Clock, class Duration>

constexpr time_point<Clock, ToDuration> time_point_cast(

                                 const time_point<Clock, Duration> &t);
(C++14 起)

std::chrono::time_point 从一个 duration 到另一个。

目录

示例

t - 转换来源的 time_point

返回值

std::chrono::time_point<Clock, ToDuration>(std::chrono::duration_cast<ToDuration>(t.time_since_epoch()))

注意

time_point_cast 将仅若 ToDurationduration 的实例才参与重载决议。

示例

#include <iostream>
#include <chrono>
 
using Clock = std::chrono::high_resolution_clock;
using Ms = std::chrono::milliseconds;
using Sec = std::chrono::seconds;
 
template<class Duration>
using TimePoint = std::chrono::time_point<Clock, Duration>;
 
inline void print_ms(const TimePoint<Ms>& time_point) 
{
    std::cout << time_point.time_since_epoch().count() << " ms\n";
}
 
int main() 
{
    TimePoint<Sec> time_point_sec(Sec(4));
 
    // 隐式转换,无精度损失
    TimePoint<Ms> time_point_ms(time_point_sec);
    print_ms(time_point_ms); // 4000 ms
 
    time_point_ms = TimePoint<Ms>(Ms(5756));
 
    // 显式转型,在精度损失可能发生时需要
    // 5756 truncated to 5000
    time_point_sec = std::chrono::time_point_cast<Sec>(time_point_ms);
    print_ms(time_point_sec); // 5000 ms
}

输出:

4000 ms
5000 ms

版本历史

  • (当前 | 先前 2017年10月10日 (二) 19:06Fruderica讨论 | 贡献 . . (1,873字节) (-10). . (撤销)
  • 当前 | 先前 2017年10月10日 (二) 19:05Fruderica讨论 | 贡献. . (1,883字节) (+554). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 16:42P12bot讨论 | 贡献 . . (1,329字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 07:22P12bot讨论 | 贡献 . . (1,329字节) (-24). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 14:43P12bot讨论 | 贡献 . . (1,353字节) (+361). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 09:51P12讨论 | 贡献 . . (992字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (992字节) (-38). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 13:15P12讨论 | 贡献 . . (1,030字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,030字节) (+1,030). . (Translated from the English version using Google Translate)