简体   繁体   中英

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM