Converting boost::chrono::steady_clock::time_point to std::chrono::steady_clock::time_point

1.3k views Asked by At

Is there any elegant way of converting the boost chrono time_point to the standard library equivalent?

1

There are 1 answers

1
md5i On BEST ANSWER

You can't guarantee a conversion, I am afraid, unless you accept a priori that boost::chrono::steady_clock and std::chrono::steady_clock have the same epoch. If you can accept this, then something like the following could work:

#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);
}