gpt4 book ai didi

C++ 协程/Visual Studio : How can a generator call a function that yields values on its behalf?

转载 作者:行者123 更新时间:2023-11-30 00:45:36 31 4
gpt4 key购买 nike

协程定义为 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4628.pdf并在 VS2015/Update 3 中实现,生成器如何调用代表它发出值的函数?

说明示例

我想编写如下代码...

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 委托(delegate)给另一个生成器。但是创建一个可以的 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;
}

关于C++ 协程/Visual Studio : How can a generator call a function that yields values on its behalf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801560/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com