为什么有一个静态函数返回 std::chrono::duration 类型的零表示?
是不是:
std::chrono seconds s;
s = std::chrono::seconds(0);
完全一样:std::chrono::seconds s;
s = std::chrono::seconds::zero()
?是否有一个通用的 chrono::duration::zero 对象/函数,它具有到每个持续时间类型的隐式转换?这在非模板情况下可能很有用。
seconds s = durationZero;
minutes m = durationZero;
这样,更改持续时间类型/精度不会影响“零分配”。
最佳答案
在zero
的持续时间的情况下,是为了给实现提供一些灵活性。不代表 Rep(0)
.
std::chrono::duration<Rep,Period>::zero
If the representation
rep
of the duration requires some other implementation to return a zero-length duration,std::chrono::duration_values
can be specialized to return the desired value.
如果你使用
std::chrono::seconds(0)
就没有问题了但如果你使用模板,那么 some_duration::zero()
将代表零持续时间,但 some_duration(0)
也许不会。或者,如果您想弄清楚是否过去了一段时间,并且您不能或不想对
duration
做出任何假设类型。auto t1 = some_clock::now();
// so something
auto t2 = some_clock::now();
some_clock::duration d = t2 - t1; // where you don't want to make any assumtions about duration
if ( d == some_clock::duration::zero() ) {
// no time elapsed according to some_clock
}
你也许总是可以投 std::chrono::seconds(0)
到其他表示,但使用 some_duration::zero()
更清楚如果您想获得零持续时间 if some_duration
基于模板参数。我从来没有遇到过这样的用例,目前我也找不到有意义的例子。如果您想这样做,我唯一想到的是温度相关
zero
始终为 0°C,因此对于°F 和°K,zero
将返回不同的值.
关于c++ - std::chrono::duration::zero() 的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64877472/