Spec-Zone.ru › C++

std::chrono::time_point_cast

Определено в заголовочном файле <chrono>
template< class ToDuration, class Clock, class Duration >
std::chrono::time_point<Clock, ToDuration>
    time_point_cast( const std::chrono::time_point<Clock, Duration> &t );
(начиная с C++11)
(до C++14)
template< class ToDuration, class Clock, class Duration >
constexpr std::chrono::time_point<Clock, ToDuration>
    time_point_cast( const std::chrono::time_point<Clock, Duration> &t );
(начиная с 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 conversion, 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

См. также

floor(std::chrono::time_point)
(C++17)
преобразует time_point в другой time_point с округлением вниз
(шаблон функции)
ceil(std::chrono::time_point)
(C++17)
преобразует time_point в другой time_point с округлением вверх
(шаблон функции)
round(std::chrono::time_point)
(C++17)
преобразует time_point в другой time_point с округлением до ближайшего значения; при равном расстоянии округляет до чётного
(шаблон функции)
duration_cast
(C++11)
преобразует duration в другую duration с иным интервалом тиков
(шаблон функции)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/chrono/time_point/time_point_cast

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API