问题描述
我正在使用boost :: asio :: deadline_timer,以便在 tcp套接字上的async_read
操作之前设置一些超时.我正在使用 boost 1.61 .
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));
问题:
我代码的其他部分使用std::chrono::milliseconds
.我想使用std::chrono
而不是"long time_out_millis"
&如果可能,请使用std::chrono::milliseconds
而不是boost::posix_time::milliseconds
.我该怎么办?
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?
问题:
那么,如何在这里使用std::chrono::milliseconds
呢?我可以从std::chrono::milliseconds
投射到boost::posix_time::milliseconds
吗?
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
?
推荐答案
直接解决方案: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.
在任何c ++ 11或更高版本的场景中,
In any c++11 or higher scenario, simply
#include <boost/asio/high_resolution_timer.hpp>
从下到上享受完全在std::chrono
上参数化的计时器.不再有阻抗不匹配的情况:
And enjoy a timer completely parameterized on std::chrono
from bottom to top. No more impedance mismatch:
#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);
}
请注意,这会更改您的
long time_out_millis = 2000;
变成类似
Clock::duration timeout = 2000ms;
这篇关于如何将`std :: chrono :: milliseconds`转换为`boost :: posix_time :: milliseconds`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!