Namespaces
Variants

std::chrono::year:: ok

From cppreference.net
constexpr bool ok ( ) const noexcept ;
(C++20 起)

检查存储在 * this 中的年份值是否处于有效范围内,即 [ - 32767 , 32767 ]

返回值

若存储在 * this 中的年份值处于 [ - 32767 , 32767 ] 范围内,则为 true ;否则为 false

可能的实现

查看实现位于 libstdc++ libc++ 、 以及 Howard Hinnant 的 date.h

class Year
{
    short year_;   // 仅用于说明
public:
    bool ok() const noexcept { return year_ != std::numeric_limits<short>::min(); }
    /*...*/
};

示例

#include <chrono>
#include <iomanip>
#include <iostream>
int main()
{
    std::cout << "输入年份 │ 内部值 │ ok()\n" << std::boolalpha;
    for (const int i : {2020, 0x8000, 0x8001, 0xFFFF, 0x18000})
    {
        const std::chrono::year y{i};
        std::cout << std::setw(10) << i << " │ "
                  << std::setw(14) << static_cast<int>(y) << " │ "
                  << y.ok() << '\n';
    }
}

可能的输出:

输入年份 │ 内部值 │ ok()
      2020 │           2020 │ true
     32768 │         -32768 │ false
     32769 │         -32767 │ true
     65535 │             -1 │ true
     98304 │         -32768 │ false