std::chrono::time_point_cast
来自cppreference.com
< cpp | chrono | time point
在标头 <chrono> 定义
|
||
template< class ToDuration, class Clock, class Duration > std::chrono::time_point<Clock, ToDuration> |
(C++11 起) (C++14 前) |
|
template< class ToDuration, class Clock, class Duration > constexpr std::chrono::time_point<Clock, ToDuration> |
(C++14 起) | |
将 std::chrono::time_point 从一个时长转换到另一个。
time_point_cast
仅当 ToDuration
为 std::chrono::duration 的特化时才参与重载决议。
示例
t | - | 转换来源的 time_point
|
返回值
std::chrono::time_point<Clock, ToDuration>(
std::chrono::duration_cast<ToDuration>(t.time_since_epoch()))。
示例
运行此代码
#include <chrono> #include <iostream> using namespace std::chrono_literals; 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{4s}; // 隐式转换,无精度损失 TimePoint<Ms> time_point_ms{time_point_sec}; print_ms(time_point_ms); // 4000 ms time_point_ms = TimePoint<Ms>{5756ms}; print_ms(time_point_ms); // 5756 ms // 显式转换,在可能发生精度损失时需要 // 5756 截断为 5000 time_point_sec = std::chrono::time_point_cast<Sec>(time_point_ms); print_ms(time_point_sec); // 5000 ms }
输出:
4000 ms 5756 ms 5000 ms
参阅
转换 time_point 到另一个,向下取整 (函数模板) | |
转换 time_point 到另一个,向上取整 (函数模板) | |
转换 time_point 到另一个,就近取整,偶数优先 (函数模板) | |
(C++11) |
转换时长到另一个拥有不同计次间隔的时长 (函数模板) |