What is the purpose of std::chrono::duration::zero()

Viewed 420

Why is there a static function that returns the zero representation of a std::chrono::duration type ?

Isn't:

std::chrono seconds s;
s = std::chrono::seconds(0);

exactly the same as:

std::chrono::seconds s;
s = std::chrono::seconds::zero()

?


And is there a generic chrono::duration::zero object/function, that has an implicit conversion into each duration type ? That may be useful in a non-template situation.

seconds s = durationZero;
minutes m = durationZero;

This way, changing the duration type/precision would not affect the "zero assignments".

1 Answers

It is to give some flexibility to the implementation, in the case where the duration of zero is not represented by 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.

It won't be a problem if you use std::chrono::seconds(0) but if you use templates then some_duration::zero() would represent zero duration, but some_duration(0) might not.

Or if you want to figure out if some time elapsed, and you can't or don't want to make any assumptions about the duration type.

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
}

You might be always able cast std::chrono::seconds(0) to that other representation, but it is clearer to use some_duration::zero() if you want to get a zero duration if some_duration is based on a template argument.

I never encountered a use-case for that, and I currently also can't find a meaningful example. The only thing that comes to my mind is temperature related if you want to that zero is always 0°C, so for a °F and °K it would return different values for zero.

Related