std::chrono::round(std::chrono::duration)
来自 cppreference.cn
定义于头文件 <chrono> |
||
template< class ToDuration, class Rep, class Period > constexpr ToDuration round( const std::chrono::duration<Rep, Period>& d ); |
(自 C++17 起) | |
返回可使用 ToDuration
表示且最接近 d 的值 t
。若存在两个这样的值,则返回偶数值(即满足 t % 2 == 0 的值 t
)。
除非 ToDuration
是 std::chrono::duration 的特化,且 std::chrono::treat_as_floating_point_v<typename ToDuration::rep> 为 false,否则此函数不参与重载决议。
内容 |
[编辑] 参数
d | - | 要转换的持续时间 |
[编辑] 返回值
舍入到最接近 ToDuration
类型持续时间的 d,在中间情况时舍入到偶数。
[编辑] 可能的实现
namespace detail { template<class> inline constexpr bool is_duration_v = false; template<class Rep, class Period> inline constexpr bool is_duration_v< std::chrono::duration<Rep, Period>> = true; } template<class To, class Rep, class Period, class = std::enable_if_t<detail::is_duration_v<To> && !std::chrono::treat_as_floating_point_v<typename To::rep>>> constexpr To round(const std::chrono::duration<Rep, Period>& d) { To t0 = std::chrono::floor<To>(d); To t1 = t0 + To{1}; auto diff0 = d - t0; auto diff1 = t1 - d; if (diff0 == diff1) { if (t0.count() & 1) return t1; return t0; } else if (diff0 < diff1) return t0; return t1; } |
[编辑] 示例
运行此代码
#include <chrono> #include <iomanip> #include <iostream> int main() { using namespace std::chrono_literals; std::cout << "Duration\tFloor\tRound\tCeil\n"; for (using Sec = std::chrono::seconds; auto const d : {+4999ms, +5000ms, +5001ms, +5499ms, +5500ms, +5999ms, -4999ms, -5000ms, -5001ms, -5499ms, -5500ms, -5999ms}) std::cout << std::showpos << d << "\t\t" << std::chrono::floor<Sec>(d) << '\t' << std::chrono::round<Sec>(d) << '\t' << std::chrono::ceil <Sec>(d) << '\n'; }
输出
Duration Floor Round Ceil +4999ms +4s +5s +5s +5000ms +5s +5s +5s +5001ms +5s +5s +6s +5499ms +5s +5s +6s +5500ms +5s +6s +6s +5999ms +5s +6s +6s -4999ms -5s -5s -4s -5000ms -5s -5s -5s -5001ms -6s -5s -5s -5499ms -6s -5s -5s -5500ms -6s -6s -5s -5999ms -6s -6s -5s
[编辑] 参见
(C++11) |
将持续时间转换为另一个,具有不同的节拍间隔 (函数模板) |
(C++17) |
将持续时间转换为另一个,向下舍入 (函数模板) |
(C++17) |
将持续时间转换为另一个,向上舍入 (函数模板) |
将 time_point 转换为另一个,舍入到最近, ties to even (函数模板) | |
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) |
最接近的整数,在中间情况时远离零舍入 (函数) |