std::chrono::year::ok
来自 cppreference.cn
| 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_; // exposition-only public: bool ok() const noexcept { return year_ != std::numeric_limits<short>::min(); } /*...*/ }; |
[编辑] 示例
运行此代码
#include <chrono> #include <iomanip> #include <iostream> int main() { std::cout << "input year │ internal value │ 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'; } }
可能的输出
input year │ internal value │ ok()
2020 │ 2020 │ true
32768 │ -32768 │ false
32769 │ -32767 │ true
65535 │ -1 │ true
98304 │ -32768 │ false