chrono :: month和chrono :: months有什么区别

问题描述 投票:11回答:1

C ++ 20计时类型/值month{7}months{7}有什么区别?有两个这样的相似名称难道令人困惑吗?

c++ c++20 chrono
1个回答
17
投票

是,第一次遇到该库时同时具有monthmonths可能会造成混淆。但是,此库中有一致的命名约定,以帮助减少这种混淆。这样做的好处是可以清晰区分不同的语义,同时保留简短的直观名称。

months

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

  • nanoseconds
  • microseconds
  • milliseconds
  • seconds
  • minutes
  • hours
  • days
  • months
  • years

所以monthschrono::duration type

使用月份= duration << [[至少20位的有符号整数类型,                         ratio_divide >>;
它正好是chrono::duration

1 / 12。

years
您可以这样打印出来:

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

输出为:

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

这是2 629,746秒的7个单位。事实证明,2,629,746秒是民用日历中月份的平均长度。换句话说:

7[2629746]s

(确切的数字除了赢得小额下注之外不是特别重要)

static_assert(months{1} == 2'629'746s); 另一方面,

month(单数)是

not a month。它是民用日历中一年中一个月的calendrical specifier。或:

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

static_assert(month{7} == July);

auto independence_day = month{7}/4d/2020y;
month的代数反映了这些不同的语义。例如,“七月+七月”是毫无意义的,因此是编译时错误:

months

但是这很合理:

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});
day之间有相似的关系。在daysyear之间。


如果为复数,则为years


而且只有chrono::duration具有类型安全性,以帮助您确保这两个语义上不同但又相似的概念不会在您的代码中相互混淆。
© www.soinside.com 2019 - 2024. All rights reserved.