问题
I am using a boost::asio::deadline_timer like so to set some timeout before an async_read
operation on a tcp socket. I am using boost 1.61.
long time_out_millis = 2000;
boost::asio::deadline_timer theTimer(theSocket.get_io_service(), boost::posix_time::milliseconds(time_out_millis));
Problem:
Other parts of my code use std::chrono::milliseconds
. I want use std::chrono
instead of the "long time_out_millis"
& if possible use std::chrono::milliseconds
instead of boost::posix_time::milliseconds
. How can I do that?
Question:
So, how can I use std::chrono::milliseconds
here ? Is there a way I cast from std::chrono::milliseconds
to boost::posix_time::milliseconds
?
回答1:
Direct solution: duration_cast<>
:
using namespace std::chrono;
using namespace std::chrono_literals;
boost::posix_time::seconds(duration_cast<milliseconds>(2s).count());
Still not nice. But this is your key.
BETTER NEWS
In any c++11 or higher scenario, simply
#include <boost/asio/high_resolution_timer.hpp>
And enjoy a timer completely parameterized on std::chrono
from bottom to top. No more impedance mismatch:
Live On Coliru
#include <boost/asio/high_resolution_timer.hpp>
using namespace std::chrono_literals;
int main() {
boost::asio::io_service svc;
boost::asio::high_resolution_timer tim(svc);
tim.expires_from_now(1s);
tim.expires_from_now(100ms);
tim.expires_from_now(3h);
tim.expires_from_now(15'000us);
tim.expires_from_now(15'000'000ns);
}
Note this would change your
long time_out_millis = 2000;
Into something like
Clock::duration timeout = 2000ms;
来源:https://stackoverflow.com/questions/47563212/how-to-cast-stdchronomilliseconds-to-boostposix-timemilliseconds