【问题标题】:std::chrono::time_point invalid valuestd::chrono::time_point 无效值
【发布时间】:2016-10-13 12:54:09
【问题描述】:
boost/std :: chrono::time_point my_time_point( /* invalid value */ );

我需要存储一个无效/无意义/哨兵值。我怎么可能这样做?

【问题讨论】:

  • 查看 boost::optional 或 std::optional: boost.org/doc/libs/1_61_0/libs/optional/doc/html/index.html
  • 你确定这会有所帮助吗?我需要my_time_point 来存储无效值
  • “可选”的要点是在您选择的域中提供一个“额外值”,表示“空”/“无效”状态
  • 现在在我看来,std/boost::chrono (stackoverflow.com/questions/25880503/…) 中没有无效值之类的东西。不管怎样,谢谢你的努力
  • 为什么所有的反对票?对我来说似乎是一个合理的问题。

标签: c++


【解决方案1】:

你可以使用boost::optional(或者std::optional如果你支持C++17)来表示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.)

【讨论】:

  • 赞成,但挑剔:OP询问的是std::chrono::time_point,而不是boost::chrono::time_point。 :-)
  • @HowardHinnant:已修复!
【解决方案2】:

我有同样的要求,结果发现有一个优雅的解决方案。如果您可以将 TimePoint 设置为未来 {Fri Apr 11 23:47:16 2262} 的不合理的大值,那么这样做应该很简单。

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;

警告:此帖子将导致 Y2262 问题。但到那时,我们应该在标准中有更好的类型。

【讨论】:

  • Warning: This post will lead to a Y2262 problem. But by then we should have better types in the standard. - 不要赌它:)
  • 为什么不使用 timepoint::min 而不是 timepoint::max?效果相同,但没有 YXXXX 错误的风险
猜你喜欢
  • 1970-01-01
  • 2020-10-13
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多