Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::chrono::time_point invalid value

Tags:

c++

boost/std :: chrono::time_point my_time_point( /* invalid value */ );

I am in need to store an invalid/nonsensical/sentinel value. How can I possibly do that?

like image 223
user3600124 Avatar asked Oct 13 '16 12:10

user3600124


People also ask

What is std :: Chrono :: Time_point?

Class template std::chrono::time_point represents a point in time. It is implemented as if it stores a value of type Duration indicating the time interval from the start of the Clock 's epoch. Clock must meet the requirements for Clock or be std::chrono::local_t (since C++20).

What does std :: Chrono :: System_clock :: now return?

std::chrono::system_clock::now Returns a time point representing with the current point in time.


2 Answers

You can use boost::optional (or std::optional if you have C++17 support) to represent an invalid state of chrono::time_point:

#include <chrono>
#include <boost/optional.hpp>

int main()
{
    using my_clock = std::chrono::system_clock;
    using my_time_point = std::chrono::time_point<my_clock>;

    boost::optional<my_time_point> maybe_time_point;

    // Set to invalid value:
    maybe_time_point = boost::none;

    // If 'maybe_time_point' is valid...
    if(maybe_time_point) 
    { 
        auto inner_value = *maybe_time_point;
        /* ... */
    }
    else { /* ... */ }
}

(You can run it on wandbox.)

like image 54
Vittorio Romeo Avatar answered Oct 24 '22 04:10

Vittorio Romeo


I had the same requirement and turns out there is an elegant solution. If you are OK to set TimePoint to a unreasonably large value into the future {Fri Apr 11 23:47:16 2262} then it should be simple to do this.

using Clock = std::chrono::high_resolution_clock;
using TimePoint = std::chrono::time_point<Clock>;
constexpr TimePoint invalidTime_k = TimePoint::max();

TimePoint my_time_point = invalidTime_k;

Warning: This post will lead to a Y2262 problem. But by then we should have better types in the standard.

like image 4
Ram Avatar answered Oct 24 '22 05:10

Ram