C++20 计时类型/值之间有什么区别 month{7}
和 months{7}
?有两个如此相似的名字是不是很困惑?
最佳答案
是的,同时拥有 month
可能会令人困惑。和 months
第一次遇到这个库时。然而,这个库中有一致的命名约定来帮助减少这种混淆。好处是在保留简短的直观名称的同时,清楚地分离了不同的语义。months
所有“预定义”chrono::duration
类型是复数:
nanoseconds
microseconds
milliseconds
seconds
minutes
hours
days
weeks
months
years
所以
months
是 chrono::duration
type :using months = duration<signed integer type of at least 20 bits, ratio_divide<years::period, ratio<12>>>;
And it is exactly 1/12 of years
.
static_assert(12*months{1} == years{1});
你可以像这样打印出来:
cout << months{7} << '\n';
输出是:
7[2629746]s
这读取为 2,629,746 的 7 个单位。事实证明,2,629,746 秒是公历中一个月的平均长度。不同的说法:
static_assert(months{1} == 2'629'746s);
(确切的数字不是特别重要,除了赢得酒吧投注)
month
month
(单数)另一方面不是 chrono::duration
.它是民用日历中一年中一个月的日历说明符。或者:static_assert(month{7} == July);
这可用于形成这样的日期:
auto independence_day = month{7}/4d/2020y;
month
的代数和 months
反射(reflect)这些不同的语义。例如“July + July”是无意义的,因此是编译时错误:auto x = month{7} + month{7};
~~~~~~~~ ^ ~~~~~~~~
error: invalid operands to binary expression ('std::chrono::month' and 'std::chrono::month')
但这完全有道理:
auto constexpr x = month{7} + months{7};
static_assert(x == February);
而这个:
auto constexpr x = months{7} + months{7};
static_assert(x == months{14});
然而:
auto b = February == months{14};
~~~~~~~~ ^ ~~~~~~~~~~
error: invalid operands to binary expression ('const std::chrono::month' and 'std::chrono::months')
即
month
和 months
不仅不相等,甚至没有可比性。如果你喜欢水果类比的话,它们就是苹果和橙子。 ;-)day
之间也有类似的关系和 days
.和之间 year
和 years
.If it is plural, it is a
chrono::duration
.
并且只有
<chrono>
具有类型安全性,可帮助您确保这两个语义不同但相似的概念不会在您的代码中相互混淆。
关于c++ - chrono::month 和 chrono::months 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62249520/