提问者:小点点

chrono::months和chrono::months之间有什么区别


C++20 chrono类型/值月份{7}月份{7}有什么区别? 有两个如此相似的名字,不是让人摸不着头脑吗?


共1个答案

匿名用户

是的,当第一次遇到此库时,同时具有可能会令人困惑。 但是,在这个库中有一致的命名约定来帮助减少这种混乱。 这样做的好处是在保留简短直观的名称的同时,清晰地分离出不同的语义。

所有“预定义”chrono::duration类型都是复数:

  • 纳秒
  • 微秒
  • 毫秒
  • 分钟
  • 小时
  • 天数
  • 月份

因此monthschrono::duration类型:

using months = duration<signedinteger type of at least 20 bits,
                         ratio_divide<years::period, ratio<12>>>;

而且正好是1/12

static_assert(12*months{1} == years{1});

你可以这样打印出来:

cout << months{7} << '\n';

输出为:

7[2629746]s

这表示为7个单位,共2,629,746 s。 原来,2,629,746秒是民用日历中一个月的平均长度。 不同的说法:

static_assert(months{1} == 2'629'746s);

(除了中奖酒吧投注外,确切数字并不是特别重要)

另一方面,month(单数)不是chrono::duration。 它是民用日历中一年中某一个月的历法说明符。 或者:

static_assert(month{7} == July);

这可以用来形成这样的日期:

auto independence_day = month{7}/4d/2020y;

monthmonths的代数反映了这些不同的语义。 例如,“jury+jury”是不合理的,因此是编译时错误:

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});

之间也有类似的关系。 以及之间。

如果是复数,则为chrono::duration

并且只有具有类型安全性,可以帮助您确保这两个语义不同但又相似的概念不会在代码中相互混淆。