您可以使用绑定的函数对象来包含状态。
事实上,绑定函数对象可以优雅地表示为带有捕获的 lambda。确保捕获是按值进行的(这样您就不会意外地与其他实例共享状态),如果不是,它们引用的对象的生存时间足够长。
例如
extern std::ostream& log_stream; // for exposition only
struct coroutine_work {
boost::uuids::uuid the_magic_request_id = boost::uuids::random_generator{}();
void operator()(boost::asio::yield_context yield) {
async_foo(yield);
some_function();
}
void some_function() const {
log_stream << the_magic_request_id << " Some function called\n";
}
}
或者:
static void some_function(boost::uuids::uuid const& reqid) const {
log_stream << reqid << " Some function called\n";
}
struct coroutine_work {
boost::uuids::uuid the_magic_request_id = boost::uuids::random_generator{}();
void operator()(boost::asio::yield_context yield) {
async_foo(yield);
some_function(the_magic_request_id);
}
}
或转化为 lambda 形式:
static void some_function(boost::uuids::uuid const& reqid) const {
log_stream << reqid << " Some function called\n";
}
// somewhere else:
{
boost::uuids::uuid the_magic_request_id = boost::uuids::random_generator{}();
auto coroutine_work = [the_magic_request_id](boost::asio::yield_context yield) {
async_foo(yield);
some_function(the_magic_request_id);
}
}