代码之家  ›  专栏  ›  技术社区  ›  Danny

嘿,伙计们,试图使用std::chrono为时间添加持续时间,我搞砸了什么?

  •  0
  • Danny  · 技术社区  · 5 年前

    所以,我的代码没有编译,但我很想编译。这是我的代码:

    float numSeconds = 50;
    std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now();
    auto duration = std::chrono::duration<float, std::chrono::seconds>(numSeconds);
    startTime -= duration;
    

    看起来应该很简单,但在尝试就地减法时,我遇到了一个运算符未找到的错误。有什么建议吗?我还尝试将第三行替换为以下内容:

       auto duration = std::chrono::duration<float, std::ratio<1, 1>>(numSeconds);
    

    然而,这条线似乎不是问题的原因,这两种方法似乎都是有效的。我最后一句话还是不开心。

    编辑:我发布的原始代码中有一个拼写错误,所以大多数答案与我的实际问题无关。我得到的错误代码在最后一行:

    "Error  C2679   binary '-=': no operator found which takes a right-hand operand of type 'std::chrono::duration<float,std::chrono::seconds>' (or there is no acceptable conversion)"
    

    此外,当我将最后一行更改为:

    timer.m_startTime = timer.m_startTime - duration;
    

    我得到以下错误代码:

    Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'std::chrono::time_point<std::chrono::steady_clock,std::chrono::duration<float,std::ratio<1,1000000000>>>' (or there is no acceptable conversion)
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   tangy    5 年前

    Reference Code Link

    问题

    1. 正如评论中所指出的,在第2行,返回类型为 std::chrono::steady_clock::now() 是 std::chrono_time_point .
    2. 提供给的第二个模板参数 std::chrono::duration 不符合指定的要求。例如,您会注意到编译错误 static assertion failed: period must be a specialization of ratio 对应于这条线。
    3. 最后,未找到运算符是因为没有相应的运算符 -= 提供的不受支持的模板参数的运算符。

    解决方案

    • 您可以使用std::ratio<1,1>;代表秒。
    auto duration = std::chrono::duration<std::int64_t, std::ratio<1,1>>(numSeconds);
     // or simply std::chrono::seconds(numSeconds)
    
    • 尝试使用浮点类型来表示时间可能不是一个好主意( Why? ). 最好使用较小的单位(例如毫秒而不是秒),或者如果你坚持使用浮点类型,你需要一个较大的类型,例如double(链接文档对此进行了解释)。这样的事情似乎让你的例子奏效了。
    double numSeconds = 50.0;
    using FpDurationT = std::chrono::duration<double, std::ratio<1,1>>;
    using TimepointT = std::chrono::time_point<std::chrono::steady_clock, FpDurationT>;
    TimepointT startTime = std::chrono::steady_clock::now();
    auto duration = FpDurationT(numSeconds);
    startTime -= duration;