Reputation: 2605
I have a function that has this signature:
void checkTime (const std::chrono::time_point<std::chrono::system_clock> &time)
{
//do stuff...
}
I need to call the above function like this:
void wait_some_time (unsigned int ms)
{
//do stuff...
checkTime(ms); //ERROR: How can I cast unsigned int to a time_point<system_clock> as now() + some milliseconds?
//do more stuff...
}
I want to use like this:
wait_some_time(200); //wait now + 200ms
Question:
How can I cast 'unsigned int' to a const std::chrono::time_point that has the milliseconds value ?
Thanks!
Upvotes: 3
Views: 11388
Reputation: 1884
You can construct a time_pont
with a duration
, and you can construct a duration
with unsigned int
, so
using TimePoint = std::chrono::time_point<std::chrono::system_clock>;
using Duration = std::chrono::duration<unsigned int, std::milli>;
checkTime(TimePoint(Duration(ms)));
... although I don't really see what you want to achieve :)
EDIT: If you want now + ms, you can write
std::chrono::system_clock::now() + Duration(ms)
Upvotes: 3
Reputation: 171313
How can I cast 'unsigned int' to a const std::chrono::time_point that has the milliseconds value ?
A time_point
is a point in time, represented as an offset to some epoch (the "zero" value for the time_point). For system_clock
the epoch is 00:00:00 Jan 1 1970.
Your unsigned int
is just an offset, it can't be converted directly to a time_point
because it has no epoch information associated with it.
So to answer the question "how do you convert an unsigned int
to a time_point
?" you need to know what the unsigned int
represents. The number of seconds since the epoch started? The number of hours since you last called the function? A number of minutes from now?
If what it's meant to mean is "now + N milliseconds" then N corresponds to a duration
, measured in units of milliseconds. You can convert it to that easily with std::chrono::milliseconds(ms)
(where the type milliseconds
is a typedef for something like std::chrono::duration<long long, std::milli>
i.e. a duration represented as a signed integer type in units of 1000th of a second).
Then to get the time_point corresponding to "now + N milliseconds" you just add that duration
to a time_point
value for "now" obtained from the relevant clock:
std::chrono::system_clock::now() + std::chrono::milliseconds(ms);
Upvotes: 5
Reputation: 13440
If you are using C++14 you can simplify it by using this
auto later = std::chrono::steady_clock::now() + 500ms;
But even without 14 I would alter your function definition to:
void wait_some_time (std::chrono::milliseconds ms);
and then just add the milliseconds to your steady_clock. If you really want to support an integer, you could implement the operator by yourself (see cppreference for the original source)
constexpr std::chrono::milliseconds operator ""ms(unsigned long long ms)
{
return chrono::milliseconds(ms);
}
Upvotes: 3