std::chrono::time_point_cast
来自 cppreference.com
定义在头文件 <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}; // implicit cast, no precision loss 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 // explicit cast, need when precision loss may happen // 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 5756 ms 5000 ms
[编辑] 另请参阅
将 time_point 转换为另一个,向下取整 (函数模板) | |
将 time_point 转换为另一个,向上取整 (函数模板) | |
将 time_point 转换为另一个,四舍五入,舍入到偶数 (函数模板) | |
(C++11) |
将持续时间转换为另一个,使用不同的滴答间隔 (函数模板) |