C++ Logo

std-proposals

Advanced search

[std-proposals] Literal representing for chrono::days/weeks/months/years

From: Kang Hewill <hewillk_at_[hidden]>
Date: Fri, 21 Jul 2023 13:10:38 +0800
Dear experts,

C++20 introduces new duration aliases chrono::days/chrono::weeks/
chrono::months/chrono::years and along with the new Calendar types
chrono::day/chrono::week/chrono::month/chrono::year, where the latter can
add the former by addition assignment. For example:

  auto m = chrono::October;
m += chrono::months{8};

I wonder is it worth adding a literal suffix of *same name* to the former?,
which allows us to

auto m = chrono::October;
m += 8months;

I personally find this valuable because it makes the code simple and
intuitive, and it's not too difficult to implement:

   constexpr chrono::days
operator""days(unsigned long long d) noexcept
{ return chrono::days{static_cast<unsigned>(d)}; }

constexpr chrono::weeks
operator""weeks(unsigned long long w) noexcept
{ return chrono::weeks{static_cast<unsigned>(w)}; }

constexpr chrono::months
operator""months(unsigned long long m) noexcept
{ return chrono::months{static_cast<unsigned>(m)}; }

constexpr chrono::years
operator""years(unsigned long long y) noexcept
{ return chrono::years{static_cast<unsigned>(y)}; }

This allows us to write:

2004y += 300years;
100d += 20days;
auto w = chrono::Sunday;
w += 2days;

What do you experts think of this? Is this worth adding into the standard?

Hewill

Received on 2023-07-21 05:10:53