c++ - chrono::month 和 chrono::months 有什么区别

标签 c++ c++20 chrono

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

    (确切的数字不是特别重要,除了赢得酒吧投注)
    monthmonth (单数)另一方面不是 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')
    

    monthmonths不仅不相等,甚至没有可比性。如果你喜欢水果类比的话,它们就是苹果和橙子。 ;-)
    day之间也有类似的关系和 days .和之间 yearyears .

    If it is plural, it is a chrono::duration.



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

    关于c++ - chrono::month 和 chrono::months 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62249520/

    相关文章:

    c++ - 如何在没有主要功能的情况下使用片段着色器

    c++ - strstr 在 codeforces 上的 C++ 4.7 中不起作用

    c++ - 考虑到无限的 iota 并不是一个大小范围

    c++ - 您如何确保调用 Derived 析构函数?

    C++ 成员引用基类型 'Vertex *const' 不是结构或 union

    c++ - 从模块导出全局常量的正确方法是什么?

    C++20 概念检查类似元组的类型

    c++ - 如何获得 high_resolution_clock 的精度?

    C++11 Chrono - 如何将 'unsigned int' 转换为 time_point<system_clock>?

    Android NDK chrono epoch 不正确(std::chrono::high_resolution_clock)