c++ - std::chrono::duration 缺乏即时滴答计数操作的原因是什么?

标签 c++ c++11 chrono

假设我们有

#include <chrono>
#include <iostream>
#include <ctime>

namespace Ratios { typedef std::ratio<60*60*24,1> Days; }

typedef std::chrono::system_clock Clock;
typedef Clock::time_point TimePoint;

而我们的 main 看起来像

int main(int argc, char *argv[])
{
    // argc check left out for brevity
    const Clock::rep d = static_cast<Clock::rep>(std::atoi(argv[1]));
    // Right now
    TimePoint now = Clock::now();
    // Start with zero days
    auto days = std::chrono::duration<Clock::rep, Ratios::Days>::zero();

    // Now we'd like to add d to the days
    days += d; // Error!
    days.count() = d; // Error!
    days = days + d; // Error!
    days += std::chrono::duration<Clock::rep, Ratios::Days>(d); // Okay
    days = days + std::chrono::duration<Clock::rep, Ratios::Days>(d); // Okay

    days *= d; // Why is this okay?
    days %= d; // And this too?

    TimePoint later = now + days;

    return 0;
}

禁止用户直接操作duration的原因是什么?

最佳答案

这样做是为了强制您坚持使用强类型值而不是任意值。

Bjarne Stroustrup 在“C++ 编程语言”(第 4 版,35.2.1,第 1011 页)中提供了有关此行为的示例:


"The period is a unit system, so there is no = or += taking a plain value. Allowing that would be like allowing the addition of 5 of an unknown SI unit to a length in meters. Consider:

duration<long long, milli> d1{7}; // 7 milliseconds
d1 += 5; // error
[...]

What would 5 mean here? 5 seconds? 5 milliseconds? [...] If you know what you mean, be explicit about it. For example:

d1 += duration<long long, milli>{5}; //OK: milliseconds"

关于c++ - std::chrono::duration 缺乏即时滴答计数操作的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17732971/

相关文章:

c++ - 如何定义两个依赖类?

c++ - 将 CWD 设置为源目录,而不是构建目录

c++ - 在 Borland C++ 编译器 5.5 中询问文件 .obj 和 .tds

c++ - Type Alias 一个自定义类的对象

visual-studio - 编译器可以通过调用 std::chrono::system_clock::now() 重新排序代码吗?

c++ - Netbeans C++ 尝试 make.exe 的相对路径

c++ - weak_ptr 奇怪的复制构造函数

c++ - 我应该在我的类中的 std::vector 成员变量中使用 std::unique_ptr<T> 吗?

c++ - 如何在 C++11 中打印当前时间?

c++11 - 如何将 "std::chrono::system_clock::now()"转换为双倍