如何简化从clock::now()重新赋值std::chrono::sys_seconds类型time_point的语法?
简化std::chrono::sys_seconds的时间赋值语法
当我们声明了std::chrono::sys_seconds time变量后,若想通过其关联时钟获取当前时间并赋值,很多开发者会先尝试这样写:
time = decltype(time)::clock::now();
但这段代码几乎无法通过编译——原因在于decltype(time)::clock::duration是对应时钟的原生精度(通常比秒级更高,比如纳秒),而sys_seconds的精度固定为秒,两者类型不兼容,必须手动将高精度时间点转换为低精度的秒级。
因此常规的正确写法是:
time = std::chrono::time_point_cast<decltype(time)::duration>(decltype(time)::clock::now());
更简洁的实现方式
根据所使用的C++版本,有几种更清爽的写法:
C++20及以上:构造函数隐式截断
std::chrono::sys_seconds的构造函数可直接接收system_clock::time_point类型,会自动向下截断到秒级(效果等同于std::chrono::floor),代码可简化为:time = std::chrono::sys_seconds{std::chrono::system_clock::now()};若需要向上取整或四舍五入,可搭配
std::chrono::ceil或std::chrono::round:// 向上取整到最近的秒 time = std::chrono::ceil<std::chrono::seconds>(std::chrono::system_clock::now()); // 四舍五入到最近的秒 time = std::chrono::round<std::chrono::seconds>(std::chrono::system_clock::now());C++11及以上:简化time_point_cast写法
既然sys_seconds的时钟固定为system_clock,精度是seconds,可以直接显式指定参数,无需decltype推导,代码更直观:time = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());C++11及以上:用别名减少重复代码
若不想重复书写精度类型,可通过类型别名简化:using Duration = decltype(time)::duration; time = std::chrono::time_point_cast<Duration>(std::chrono::system_clock::now());
内容的提问来源于stack exchange,提问作者Ranoiaetep
相关产品推荐
相关产品推荐

