Namespaces
Variants

std::chrono:: round (std::chrono::duration)

From cppreference.net
定義先ヘッダ <chrono>
template < class ToDuration, class Rep, class Period >
constexpr ToDuration round ( const std:: chrono :: duration < Rep, Period > & d ) ;
(C++17以降)

ToDuration で表現可能な値 t のうち、 d に最も近い値を返します。そのような値が2つ存在する場合、偶数の値(つまり t t % 2 == 0 を満たす値)を返します。

この関数は、以下の条件が満たされない限りオーバーロード解決に参加しません: ToDuration std::chrono::duration の特殊化であり、かつ std:: chrono :: treat_as_floating_point_v < typename ToDuration :: rep > false である場合です。

目次

パラメータ

d - 変換する期間

戻り値

d を最も近い ToDuration 型の期間に丸めた値。中間値の場合には偶数への丸めを行います。

実装例

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;
}
**注記**: 提供されたコードはC++のテンプレートメタプログラミングとchronoライブラリを使用した`round`関数の実装です。HTMLタグ、属性、` `、`
`、``タグ内のテキスト、およびC++固有の用語(`namespace`、`template`、`constexpr`、`bool`など)は翻訳せず、元のフォーマットを保持しています。コード自体はプログラミング言語の構文であるため、翻訳の対象外です。

#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++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11)
最も近い整数(中間値の場合はゼロから遠ざかる方向に丸める)
(関数)