簡體   English   中英

檢查 std::chrono 持續時間小於 0 的慣用方法

[英]Idiomatic way to check std::chrono duration is less than 0

我知道我可以做到這一點

if (timeLeft.count() < 0)

但我想知道什么是最好的方法,因為我也可以這樣做:

if (timeLeft<std::chrono::seconds(0)) // or milliseconds or nanonseconds...

注意:我假設兩個檢查是相同的,但我不是計時專家。

編輯:完整示例:

#include<chrono>
int main(){
    const std::chrono::nanoseconds timeLeft(-5);
    if(timeLeft<std::chrono::seconds(0)){
        return 47;
    }
}

編輯 2: std::chrono::seconds(0)潛在問題是新手程序員可能會認為它涉及舍入,盡管它沒有。

表達這一點的方法之一是使用 std::chrono::duration 文字( https://en.cppreference.com/w/cpp/chrono/duration )。 它簡短而干凈:

#include<chrono>

int main(){
    using namespace std::chrono_literals;
    
    const auto timeLeft = -5ns;
    if(timeLeft<0s){
        return 47;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM