title: is it possible to overload std::chrono::duration_cast?
body: <p>I have a device that reports time as integer seconds and fractional seconds in clock ticks. For this particular device, the clock operates a 256MHz. I've defined a custom resolution that I use in duration and time_points:</p>
  <pre class="lang-cpp prettyprint-override"><code>using Res = std::chrono::duration&lt;uint64_t, std::ratio&lt;1, 256'000'000&gt;&gt;;
  </code></pre>
  <p>(unless it is pertinent, I'd rather not debate uint vs int).</p>
  <p>This resolution is adequate for representing times since 1970, with overflow around 2763.</p>
  <p>Given,</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
  #include &lt;chrono&gt;
  
  int main() {
      using Res = std::chrono::duration&lt;uint64_t, std::ratio&lt;1, 256'000'000&gt;&gt;;
      using namespace std::chrono;
      using TimePoint = time_point&lt;system_clock, Res&gt;;
  
      auto s_now = system_clock::now();
  
      auto simple = time_point_cast&lt;Res&gt;(s_now);
  
      auto s_sec = duration_cast&lt;seconds&gt;(s_now.time_since_epoch());
      auto hard = TimePoint(Res(s_sec));
      hard += duration_cast&lt;Res&gt;(s_now.time_since_epoch() - s_sec);
  
      std::cout &lt;&lt; &quot;s_now  &quot; &lt;&lt; s_now.time_since_epoch().count() &lt;&lt; &quot;\t&quot; &lt;&lt; s_sec.count() &lt;&lt; &quot;\n&quot;
                &lt;&lt; &quot;simple &quot; &lt;&lt; simple.time_since_epoch().count() &lt;&lt; &quot;\t&quot; &lt;&lt; duration_cast&lt;seconds&gt;(simple.time_since_epoch()).count() &lt;&lt; &quot;\n&quot;
                &lt;&lt; &quot;hard   &quot; &lt;&lt; hard.time_since_epoch().count()  &lt;&lt; &quot;\t&quot; &lt;&lt; duration_cast&lt;seconds&gt;(hard.time_since_epoch()).count() &lt;&lt; &quot;\n&quot;
  ;
      return 0;
  }
  </code></pre>
  <p>then <code>simple</code> is not equal to <code>hard</code>. The output might be something like this:</p>
  <pre><code>s_now  1628286679505051812  1628286679
  simple 121693484773940438   475365174
  hard   416841389953293263   1628286679
  </code></pre>
  <p>What happens is that <code>time_point_cast</code> <a href="https://stackoverflow.com/a/60425292/9220132">overflows</a> the <code>int</code> Rep for <code>system_clock::duration</code>.</p>
  <p>Based on <a href="https://stackoverflow.com/a/51226923/9220132">https://stackoverflow.com/a/51226923/9220132</a> it would seem that this is legal and moral, but it does not taste great. This limitation is a much too easy to produce source of bugs.</p>
  <p>If there were a way for me to define the implementation of casting to my very high resolution type such that I protect against overflow, that would be ideal. Knowing to use a custom helper function instead of casting is just asking for trouble, because someone will forget some time and the bug might go unnoticed into production.</p>