Question

I have a custom timer template which i want to use in std::this_thread::sleep_until(). So my now() method looks like this:

static time_point now() {
    return time_point(timer_T::now() - epoch_);
}

where epoch_ is initialized with timer_T::now(). Now i want to be able to sleep_until a specific timepoint.

    std::this_thread::sleep_until(my_timer<>::now() + std::chrono::seconds(1));

I think my problem is that i have to make time_point with my_timer<> as (template) Clock argument, but then there is now conversion between the different time_points. something like:

 using time_point = std::chrono::time_point<my_timer<timer_T>>;

The code can be found here.

How can i make this get to work? Also, is there a small chrono howto out, where i can find some information how to create a custom timer?

Was it helpful?

Solution

By looking at sleep_until, it uses the clock template argument of the time_point to query the current time. So, here is the correct way to define the time point in your code :

#include <chrono>
#include <thread>
#include <iostream>

template<typename timer_T = std::chrono::steady_clock>
class my_timer {
public:

    using timer_type = timer_T;
    using time_point = std::chrono::time_point<my_timer, typename timer_T::time_point::duration >;
    using duration   = typename timer_T::duration;
    using rep    = typename duration::rep;
    using period     = typename duration::period;

    static const bool is_steady = timer_T::is_steady;

    static time_point now() {
        return time_point(timer_T::now() - epoch_);
    }

private:
    static typename timer_T::time_point epoch_;
};

template<typename T>
typename T::time_point my_timer<T>::epoch_ = T::now();


int main(int, char*[]) {
    for(int i=0; i<5; i++) {
        std::cout << my_timer<>::now().time_since_epoch().count() << "\n";
        std::this_thread::sleep_until( my_timer<>::now() + std::chrono::seconds(3) );
    }
}

Working here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top