What is the reason behind std::chrono::duration's lack of immediate tick count manipulation?

c++, c++-chrono, c++11

Solution

It is done to enforce you to stick to strongly typed values rather than arbitrary values.

Bjarne Stroustrup has examples regarding this behaviour in "The C++ Programming Language" (4th Ed., 35.2.1, pp. 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"

Problem

Suppose we have ``` #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; ``` And our `main` looks like ``` 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; } ``` What is the reason behind prohibiting the user to manipulate a `duration` directly?

Original source