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?
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?
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.
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 { /* ... */ }
}