【发布时间】:2015-03-14 09:39:08
【问题描述】:
我正在编写一个在底层使用 Boost.Asio 的 C++11 网络库。我想公开一个允许用户使用堆栈式协程的 API。
boost::asio::yield_context 重载[] 运算符,以便异步操作可以设置错误代码而不是引发异常。例如:
std::size_t n = my_socket.async_read_some(buffer, yield[ec]);
if (ec)
{
// An error occurred.
}
我的库使用std::error_code 和std::system_error 报告错误。我的问题是如何让boost::asio::yield_context 设置std::error_code 而不是boost::system::error_code?我希望我的图书馆的用户能够这样做:
std::error_code ec;
auto result = remoteProdedureCall(args, yield[ec]);
if (ec)
handleError();
remoteProcedureCall 看起来像这样:
Result remoteProcedureCall(Args args, boost::asio::yield_context yield)
{
//...
boost::asio::async_write(socket_, argsBuffer, yield);
boost::asio::async_read(socket_, resultBuffer, yield);
if (invalidResult())
// Return a std::error_code via the yield object somehow???
// (My error codes belong to a custom error_category)
// ...
return result;
}
P.S.我应该指出我的库使用属于自定义 error_category 的错误代码。
【问题讨论】:
-
我意识到我所要求的可能是不可能的,但有人可能会找到一个聪明的技巧或黑客来完成这项工作。或者,也许我的做法是错误的。
-
一个想法可能是在
boost::asio::basic_yield_context周围使用某种包装器。 -
我可以重载
operator+(yield_context&, std::error_code&),以便它返回一个包含原始yield_context的yield_context_wrapper,以及一个指向用户std::error_code变量的指针。我还将提供一个采用yield_context的yield_context_wrapper转换构造函数。然后,我的 API 函数将采用yield_context_wrapper参数而不是yield_context,从而获得对用户的std::error_code变量的访问权限。
标签: c++ c++11 boost boost-asio coroutine