Search code examples
c++c++20c++-chrono

Why system_clock time_point can not be constructed from duration?


Browsing cppreference shows that in theory any time_point should be constructible from duration.

constexpr explicit time_point( const duration& d );
  1. Constructs a time_point at Clock's epoch plus d.

But when I try it on some compilers it does not work, on some it works.

Second lambda does not work, but surprisingly first one does.

Even more surprisingly it seems to depend on std lib implementation since clang with libc++ works.

#include <chrono>
using namespace std::chrono;
int main() {
    [] { return steady_clock::time_point(seconds(1000'000'000) + nanoseconds(1)); };
    [] { return system_clock::time_point(seconds(1000'000'000) + nanoseconds(1)); };
}

note: I know the answer, but I find it interesting so I wanted to share since I found no answer to this on SO, if nobody is interested in answering I will answer the question.


Solution

  • The durations of system_clock and steady_clock are implementation defined. On platforms where it does not have (at least) nanosecond resolution, there isn't a constructor that takes nanoseconds.

    If you add a duration_cast to an appropriate duration, then both work.

    #include <chrono>
    using namespace std::chrono;
    int main() {
        [] { return steady_clock::time_point(duration_cast<steady_clock::duration>(seconds(1000'000'000) + nanoseconds(1))); };
        [] { return system_clock::time_point(duration_cast<system_clock::duration>(seconds(1000'000'000) + nanoseconds(1))); };
    }