C++协程/Visual Studio:生成器如何调用代表它生成值的函数?
C++ coroutines / Visual Studio: How can a generator call a function that yields values on its behalf?
在VS2015/Update 3中定义 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4628.pdf 的协程,生成器如何调用代表其发出值的函数?
澄清示例
我想编写如下代码...
static void yield_for_me()
{
co_yield 27; // does not compile
// co_yield relies on hidden definitions
}
std::experimental::generator<int> testf()
{
yield_for_me();
co_yield 28;
}
。希望它能有与以下代码完全相同的结果:
std::experimental::generator<int> testf()
{
co_yield 27;
co_yield 28;
}
在函数中使用co_yield
/co_await
/co_return
会将其转换为协程,因此它需要有一个签名,允许编译器发现库类,向编译器解释该协程的含义。
Visual Studio 附带的生成器不支持将co_yield
委派给另一个生成器。但要造出可以recursive_generator
并不难。
下面是一个recursive_generator示例,它允许生成一个值或执行不同生成器的结果。
https://gist.github.com/GorNishanov/29e813139175b1c5299ad01021d2556d
recursive_generator的promise_type定义了两个yield_value
函数:
yield_value(T const&); // This one yields individual values
yield_value(recursive_generator<T>&&); // delegates to another generator
使用上面的recursive_generator,只需将yield_from_me函数的返回类型从 void 更改为 recursive_generator即可。
recursive_generator<int> yield_for_me()
{
co_yield 27;
}
recursive_generator<int> testf()
{
co_yield yield_for_me();
co_yield 28;
}
不能。这是 P0057 提出的协程模型的一个众所周知的限制。 尽管在本文中,它还描述了一个允许您执行以下操作的recursive_generator
(未包含在 MSVC 中):
recursive_generator<int> yield_for_me()
{
co_yield 27;
}
recursive_generator<int> testf()
{
co_yield yield_for_me();
co_yield 28;
}
顺便说一句,这样的事情是在 CO2 中实现的,这是对所提出模型的模拟。
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?