user3639557 user3639557 - 3 months ago 15
C++ Question

Is there a way to assign zero to std::chrono::nanoseconds

Is there a way to assign zero to a duration of type

std::chrono::nanoseconds
? I tried
duration::zero
but it failed.

Answer

There is a zero() function:

std::chrono::nanoseconds dur;
// ...
dur = std::chrono::nanoseconds::zero();

Or you could assign it to a temporary of type nanoseconds explicitly constructed with 0:

dur = std::chrono::nanoseconds{0};

which is what zero() returns too.

Lastly, if you're using a compiler that supports it, there is just:

// requires either "using namespace std::chrono_literals;" or "using namespace std::chrono;"
dur = 0ns;