yohhoyの日記

技術的メモをしていきたい日記

演算子オーバーロード for 日付リテラル

C++20標準ヘッダ <chrono> カレンダー(Calendar)ライブラリが提供する、日付リテラル表記用の/演算子オーバーロード一覧。

ノート:年月日順で日付リテラルを述する場合、少なくとも年(year)フィールドは常に型を明示した方がトラブルリスク*1が小さい。/演算子は左結合となることをお忘れなく。

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

// 2022-06-13
auto date1 = 2022y/6/13;    // OK: year_month_day{year{2022}, month{6}, day{13}}
auto date2 = 2022/June/13;  // NG: ill-formed
auto date3 = 2022/6/13d;    // NG: month_day{month{337}, day{13}}
auto date4 = 2022/6/13;     // NG: int{25}

auto date2m = 2022/(June/13);  // OK: 意図通りに解釈されはするものの
auto date2d = 2022/(6/13d);    // OK: これらの難解表記は避けるべき…

年月日指定:*2

左辺 右辺 結果 表記
year month year_month 年/月 *
year int year_month 年/月 *
month day month_day 月/日 *
month int month_day 月/日 *
int day month_day 月/日 *
day month month_day 日/月
day int month_day 日/月
year_month day year_month_day 年+月/日 *
year_month int year_month_day 年+月/日 *
year month_day year_month_day 年/月+日 *
int month_day year_month_day 年/月+日 *
month_day year year_month_day 月+日/年
month_day int year_month_day 月+日/年

最終日指定:*3

左辺 右辺 結果 表記
month last_spec month_day_last 月/最終日 *
int last_spec month_day_last 月/最終日 *
last_spec month month_day_last 最終日/月
last_spec int month_day_last 最終日/月
year month_day_last year_month_day_last 年/月+最終日 *
int month_day_last year_month_day_last 年/月+最終日 *
month_day_last year year_month_day_last 月+最終日/年
month_day_last int year_month_day_last 月+最終日/年

第n曜日指定:

左辺 右辺 結果 表記
month weekday_indexed month_weekday 月/第n曜日 *
int weekday_indexed month_weekday 月/第n曜日 *
weekday_indexed month month_weekday 第n曜日/月
weekday_indexed int month_weekday 第n曜日/月
year_month weekday_indexed year_month_weekday 年+月/第n曜日 *
year month_weekday year_month_weekday 年/月+第n曜日 *
int month_weekday year_month_weekday 年/月+第n曜日 *
month_weekday year year_month_weekday 月+第n曜日/年
month_weekday int year_month_weekday 月+第n曜日/年

最終曜日指定:*4

左辺 右辺 結果 表記
month weekday_last month_weekday_last 月/最終曜日 *
int weekday_last month_weekday_last 月/最終曜日 *
weekday_last month month_weekday_last 最終曜日/月
weekday_last int month_weekday_last 最終曜日/月
year_month weekday_last year_month_weekday_last 年+月/最終曜日 *
year month_weekday_last year_month_weekday_last 年/月+最終曜日 *
int month_weekday_last year_month_weekday_last 年/月+最終曜日 *
month_weekday_last year year_month_weekday_last 月+最終曜日/年
month_weekday_last int year_month_weekday_last 月+最終曜日/年

関連URL

*1:date3 は std::chrome::month クラスの未規定(unspecified)仕様により、大半のC++処理系で month_day{month{81}, day{13}} として保持される可能性が高い。(C++20 27.8.4.1/p1, 27.8.4.2/p1)

*2:ISO 8601準拠の記述順(年-月-日)のみをサポートするならば、表中 * 印オーバーロードのみで十分だったはず。

*3:ある月の最終日表現には std::chrono::last 定数を用いる。

*4:ある月の最終曜日を std::chrono::weekday_last 型 = std::chrono::weekday 型 + std::chrono::last 定数で表現する。

*5:C++20のベースとなったCalendarライブラリに関するCppCon 2015プレゼンテーション