10
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?

user3600124
  • 829
  • 1
  • 7
  • 19
  • 4
    Look into boost::optional or std::optional: http://www.boost.org/doc/libs/1_61_0/libs/optional/doc/html/index.html – Vittorio Romeo Oct 13 '16 at 12:55
  • You sure it would help? I need `my_time_point` to store an invalid value – user3600124 Oct 13 '16 at 12:56
  • 2
    The point of 'optional' is providing an "extra value" in the domain of your choice that represents a "null"/"invalid" state – Vittorio Romeo Oct 13 '16 at 12:59
  • It seems to me now, that there is no such thing as invalid value in std/boost::chrono ( http://stackoverflow.com/questions/25880503/what-is-the-c11-equivalent-to-boostdate-timenot-a-date-time ). Anyhow, thanks for your efforts – user3600124 Oct 13 '16 at 13:01
  • @user3600124: What Vittorio is saying is that if you wrap it with a `boost::optional` it *will* have a a null/invalid value that you can check for. – AndyG Oct 13 '16 at 13:03
  • 7
    Why all the down votes? Seems like a reasonable question to me. – Howard Hinnant Oct 13 '16 at 14:41

2 Answers2

5

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.

Ram
  • 3,045
  • 3
  • 27
  • 42
4

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.)

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416