给一个协程生成..
void my_coroutine(asio::yield_context yield) {
system::error_code ec;
my_wrapper(yield[ec]);
if (ec) {
// something went wrong
return;
}
...
}
void my_wrapper(asio::yield_context&& yield) {
asio::async_read(..., yield); // any asio async call
if (ec) {
// something went wrong
return;
}
...
}
在包装函数中,无法从传递的yield上下文访问ec。那么如何解决呢?
最佳答案
您想/ oji /使用ec
做什么?您可以访问的方式与my_coroutine已经显示的方式完全相同:
void my_wrapper(asio::yield_context&& yield) {
system::error_code ec;
asio::async_read(..., yield[ec]); // any asio async call
if (ec) {
// something went wrong
return;
}
...
}
如果您表示要进行可组合的异步操作,请参见以下模式:
基本示例:
template <typename Token>
auto async_meaning_of_life(bool success, Token&& token)
{
#if BOOST_VERSION >= 106600
using result_type = typename asio::async_result<std::decay_t<Token>, void(error_code, int)>;
typename result_type::completion_handler_type handler(std::forward<Token>(token));
result_type result(handler);
#else
typename asio::handler_type<Token, void(error_code, int)>::type
handler(std::forward<Token>(token));
asio::async_result<decltype (handler)> result (handler);
#endif
if (success)
handler(error_code{}, 42);
else
handler(asio::error::operation_aborted, 0);
return result.get ();
}
关于c++ - 如何通过我自己的函数传递boost::asio::yield_context?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60442680/