命名空间
变体
操作

std::chrono::floor(std::chrono::duration)

来自 cppreference.cn
< cpp‎ | chrono‎ | duration
 
 
 
 
定义于头文件 <chrono>
template< class ToDuration, class Rep, class Period >
constexpr ToDuration floor( const std::chrono::duration<Rep, Period>& d );
(自 C++17)

返回可以用 ToDuration 表示的,小于或等于 d 的最大时长 t

除非 ToDurationstd::chrono::duration 的特化,否则该函数不参与重载决议。

内容

[编辑] 参数

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>>>
constexpr To floor(const duration<Rep, Period>& d)
{
    To t = std::chrono::duration_cast<To>(d);
    if (t > d)
        return t - To{1};
    return t;
}

[编辑] 示例

#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

[编辑] 参见

将时长转换为另一个,具有不同的节拍间隔
(函数模板) [编辑]
将时长转换为另一个,向上舍入
(函数模板) [编辑]
将时长转换为另一个,四舍五入到最近,平局到偶数
(函数模板) [编辑]
将 time_point 转换为另一个,向下舍入
(函数模板) [编辑]
(C++11)(C++11)
不大于给定值的最近整数
(函数) [编辑]