std::chrono...:operator+=,(3)

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

πŸŽ€ NAME πŸŽ€

okay so bestie, welcome to the C++ Standard Libary page for std::chrono...:operator+=,(3) β€” yes, that's the manual name, and yes, we're about to make friends with std::chrono::year_month_weekday_last's compound assignment operators. πŸ’–

  • std::chrono::year_month_weekday_last::operator+=, -
  • std::chrono::year_month_weekday_last::operator+=,

not me pointing out that the NAME section says it twice β€” iconic repetition, honestly πŸ’…


✨ Synopsis ✨

the whole squad is constexpr and noexcept, and every single one is since C++20:

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

ngl, that's the entire lineup: overloads (1) and (2) are operator+= with std::chrono::years and std::chrono::months, and overloads (3) and (4) are operator-= with std::chrono::years and std::chrono::months. slay. ✨

Modifies the time point *this represents by the duration dy or dm. main character energy: *this is the one getting changed. πŸ’«

  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 vibe check: 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. no cap, that's literally the rule. πŸ‘‘


πŸ’– Example πŸ’–

// Run this code

#include <chrono>
#include <iostream>
using namespace std::chrono;

int main()
{
    auto ymwdl{August/Friday[last]/2022};
    std::cout << year_month_day{ymwdl} << '\n';
    ymwdl += months(2);
    std::cout << year_month_day{ymwdl} << '\n';
    ymwdl -= years(1);
    std::cout << year_month_day{ymwdl} << '\n';
}

obsessed with this little demo: it prints the date, adds months(2), prints again, subtracts years(1), and prints one last time. πŸ’…


πŸ“ Output: πŸ“

2022-08-26
2022-10-28
2021-10-29

ate. periodt. πŸ“


πŸ¦‹ See also πŸ¦‹

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

okay bye bestie πŸ’– β€” this lil page came from http://cppreference.com, dated 2024.06.10, and it's the std::chrono...:operator+=,(3) one. 🫢

πŸ“¦ where this page comes from