# std::chrono::time_point_cast

< cpp‎ | chrono‎ | time point

定义于头文件 `<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 <iostream>
    #include <chrono>

    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(Sec(4));

        // 隐式转换，无精度损失
        TimePoint<Ms> time_point_ms(time_point_sec);
        print_ms(time_point_ms); // 4000 ms

        time_point_ms = TimePoint<Ms>(Ms(5756));

        // 显式转型，在精度损失可能发生时需要
        // 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
    5000 ms

### 参阅

time_point (C++11) | 时间中的点 (类模板)
floor(std::chrono::time_point) (C++17) | 转换 time_point 到另一个，向下取整 (函数模板)
ceil(std::chrono::time_point) (C++17) | 转换 time_point 到另一个，向上取整 (函数模板)
round(std::chrono::time_point) (C++17) | 转换 time_point 到另一个，就近取整，偶数优先 (函数模板)
duration_cast (C++11) | 转换时长到另一个拥有不同嘀嗒间隔的时长 (函数模板)