Taking the first steps with <chrono>
library,
I'm starting with basic arithmetic on a days grained time_point
.
Thanks to a very useful post by @HowardHinnant,
I managed to write this:
#include <chrono>
using namespace std::chrono_literals;
int main()
{
std::chrono::sys_days d {std::chrono::January/31/2022};
d = std::chrono::days{2}; // ok
//d = 48h; // error: no match for 'operator =' with std::chrono::hours
}
What is not clear to me is why d = 48h;
isn't allowed.
The std::chrono::time_point<>::operator =
takes a duration
,
and the rvalue in that expression is a std::chrono::hours
that
in my mind represents a time duration.
What's the philosophy here? Are there different duration types
according to the measure unit that must be compatible with the
granularity of the time_point
? Why?
On the other hand, I understand why d = 2d;
gives an error,
since in this case std::literals::chrono_literals::operator""d
is a std::chrono::day
, which is not a duration (that's handy
to form a date literal, although it seems a little inconsistent
to me).
I wonder if there's a more convenient way to express
a duration literal equivalent to std::chrono::days{2}
.
CodePudding user response:
You can add hours to days. What you can't do is implicitly convert that into days again. You need a cast
d = std::chrono::time_point_cast<std::chrono::days>(d 48h);