std::chrono...::operator-=(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

🌸 std::chrono...::operator-=(3) 🌸

okay bestie, this one is from the C++ Standard Libary manual (yes, "Libary" β€” I'm not fixing the header spelling, that's literally what it says πŸ’€). It's a C++ chrono page, and yes, the title says operator-= but the page is also serving operator+= energy. We're covering both, no cap.

✨ NAME ✨

The page is literally named this mouthful, and the original repeats it twice:

std::chrono::year_month_day_last::operator+=,std::chrono::year_month_day_last::operator-=
-
std::chrono::year_month_day_last::operator+=,std::chrono::year_month_day_last::operator-=

So it's the std::chrono::year_month_day_last::operator+= and std::chrono::year_month_day_last::operator-= page. Iconic, verbose, very C++.

πŸ’… Synopsis πŸ’…

Four overloads, all constexpr, all noexcept, all since C++20. Here's the exact lineup:

constexpr std::chrono::year_month_day_last&                     (1)
(since C++20)
       operator+=( const std::chrono::years& dy ) const noexcept;
constexpr std::chrono::year_month_day_last&                     (2)
(since C++20)
       operator+=( const std::chrono::months& dm ) const noexcept;
constexpr std::chrono::year_month_day_last&                     (3)
(since C++20)
       operator-=( const std::chrono::years& dy ) const noexcept;
constexpr std::chrono::year_month_day_last&                     (4)
(since C++20)
       operator-=( const std::chrono::months& dm ) const noexcept;

So what's the vibe? It modifies the time point *this represents by the duration dy or dm. That's the main character move.

  1. Equivalent to *this = *this + dy;.
  2. Equivalent to *this = *this + dm;.
  3. Equivalent to *this = *this - dy;.
  4. Equivalent to *this = *this - dm;.
tiny but important detail: for durations that are convertible to both std::chrono::years and std::chrono::months, the years overloads (1,3) are preferred if the call would otherwise be ambiguous. That's the rule, bestie β€” don't come for me, I'm just reporting it. 🫢

πŸŽ€ Example πŸŽ€

go run this, it's giving chrono confidence:

// Run this code

#include <cassert>
#include <chrono>

int main()
{
    auto ymdl{11/std::chrono::last/2020};

    ymdl += std::chrono::years(15);
    assert(ymdl.day() == std::chrono::day(30));
    assert(ymdl.month() == std::chrono::November);
    assert(ymdl.year() == std::chrono::year(2035));

    ymdl -= std::chrono::months(6);
    assert(ymdl.day() == std::chrono::day(31));
    assert(ymdl.month() == std::chrono::May);
    assert(ymdl.year() == std::chrono::year(2035));
}

πŸ¦‹ See also πŸ¦‹

  • operator+ β€” adds or subtracts a year_month_day_last and some number of years or months
  • operator- (function) β€” (C++20)

kisses bestie πŸ’– this was the std::chrono...::operator-=(3) page from http://cppreference.com, dated 2024.06.10. Now go flex that calendar math. 🌈✨

πŸ“¦ where this page comes from