假设我们有
#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 of5
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/