检查std::chrono持续时间小于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;
}
}

edit2: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;
}
}

相关内容

最新更新