【问题标题】:Converting boost::chrono::steady_clock::time_point to std::chrono::steady_clock::time_point将 boost::chrono::steady_clock::time_point 转换为 std::chrono::steady_clock::time_point
【发布时间】:2018-06-20 12:08:25
【问题描述】:

有没有什么优雅的方法可以将 boost chrono time_point 转换为等效的标准库?

【问题讨论】:

  • std::system_clockboost::system_clock 都有 to_time_tfrom_time_t 静态函数。但是,steady_clock 的情况似乎并非如此。也许,那些time_points 可以以某种方式转换。
  • 我不明白为什么它被否决了?
  • 同意,讨厌在没有评论/标记的情况下投反对票。
  • 我也在问一个明确的问题,如果人们认为这显然是“不能做,因为类型来自不同的库”。如果问题如此明显或愚蠢,请解释原因。
  • @DanielLangr 问题是time_t不如time_point准确,呵呵,看来我需要介绍boost chrono的api依赖比。

标签: c++ c++11 boost boost-chrono


【解决方案1】:

恐怕您不能保证转换,除非您先验地接受boost::chrono::steady_clockstd::chrono::steady_clock 具有相同的纪元。如果您可以接受这一点,那么类似以下的内容可能会起作用:

#include <boost/chrono.hpp>
#include <chrono>

/* Convert from boost::ratio to std::ratio */
template <typename T> struct conv_ratio;
template <std::intmax_t N, std::intmax_t D>
struct conv_ratio<boost::ratio<N, D>> {
    using type = std::ratio<N, D>;
};
template <typename T>
using conv_ratio_t = typename conv_ratio<T>::type;

/* Convert from boost::duration to std::duration */
template <typename T> struct conv_duration;
template <typename Rep, typename Period>
struct conv_duration<boost::chrono::duration<Rep, Period>> {
    using type = std::chrono::duration<Rep, conv_ratio_t<Period>>;
};
template <typename T>
using conv_duration_t = typename conv_duration<T>::type;

/* Convert from A::time_point to B::time_point.  This assumes that A
 * and B are clocks with the same epoch. */
template <typename A, typename B>
typename B::time_point convert_timepoint_same_clock(
    typename A::time_point const & tp)
{
    return typename B::time_point(
        conv_duration_t<typename A::time_point::duration>(
            tp.time_since_epoch().count()));
}


int main()
{
    auto now_boost = boost::chrono::steady_clock::now();
    auto now_std = convert_timepoint_same_clock<
        boost::chrono::steady_clock, std::chrono::steady_clock>(now_boost);
}

【讨论】:

  • 您也可以在两个时钟上根据 time.now() 对它们进行标准化,以查看时期之间是否存在差异,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
相关资源
最近更新 更多