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?
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).
std::chrono::system_clock::now Returns a time point representing with the current point in time.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With