Home > Software engineering >  Negative time_point
Negative time_point

Time:04-05

Is a negative time_point allowed or it is just my implementation that allows this ?

#include <iostream>
#include <chrono>

using namespace std;
using namespace chrono;

int main()
{
    using sc_tp = steady_clock::time_point;
    using sc_dur = steady_clock::duration;
    sc_tp tp( sc_dur( -1 ) );
    cout << tp.time_since_epoch().count() << endl;
}

CodePudding user response:

std::chrono::nanoseconds, std::chrono::microseconds etc. are specified to be stored in a signed integer type but std::chrono::steady_clock only specifies the duration uses an arithmetic type. Every implementation I've seen uses one of the chrono helper duration types for steady_clock::duration but there is nothing in the standard requiring that to be the case so it could use an unsigned duration.

Note (thanks to Howard Hinnant) that std::chrono::system_clock does specify that the duration uses a signed type.

CodePudding user response:

steady_clock::duration is an alias for std::chrono::duration<rep, period> where rep and period are respective member aliases of the clock (https://en.cppreference.com/w/cpp/chrono/steady_clock).

You can check if rep is signed via:

 std::cout << std::is_signed< steady_clock::rep >::value;

And when it is signed, then you can call (https://en.cppreference.com/w/cpp/chrono/duration/duration)

template< class Rep2 >
constexpr explicit duration( const Rep2& r );

to construct a negative duration. time_point is here std::chrono::time_point<std::chrono::steady_clock,std::chrono::steady_clock::duration> and uses the same representation of durations.

  • Related