Robinson
Robinson

Reputation: 10132

Attempt to cast std::chrono::duration gives "rep cannot be a duration" compilation error

Sure I'm doing something dumb here but I'm having trouble compiling my simple stopwatch class. The error is:

/usr/include/c++/4.9/chrono:246:2: error: static assertion failed: rep cannot be a duration

I want to cast the difference in time between two std::chrono::high_resolution_clock to milliseconds. I'm sure this code used to work (false memory or perhaps better standards impl with 2015 over 2013).

The repo is here.

#include <iostream>
#include <chrono>

class Stopwatch final
{
public:

    using elapsed_resolution = std::chrono::milliseconds;
    using elapsed_duration = std::chrono::duration<std::chrono::milliseconds>;

    Stopwatch()
    {
        Reset();
    }

    void Reset()
    {
        reset_time = clock.now();
    }

    elapsed_duration Elapsed()
    {
        return std::chrono::duration_cast<elapsed_resolution>(clock.now() - reset_time);
    }

private:

    std::chrono::high_resolution_clock clock;
    std::chrono::high_resolution_clock::time_point reset_time;
};

int main(void)
{
    auto s = Stopwatch();

    std::cout << s.Elapsed().count() << std::endl;
}

Upvotes: 3

Views: 3012

Answers (1)

Devin L.
Devin L.

Reputation: 447

This line here:

using elapsed_duration = std::chrono::duration<std::chrono::milliseconds>;

needs to be something like this:

using elapsed_duration = std::chrono::duration<float, std::milli>;

Upvotes: 3

Related Questions