'Negative time_point
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;
}
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | 463035818_is_not_a_number |
