小编tor*_*psa的帖子

通过 c++20 协程制作 python 生成器

假设我有这个 python 代码:

def double_inputs():
    while True:
        x = yield
        yield x * 2
gen = double_inputs()
next(gen)
print(gen.send(1))
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,它打印“2”。我可以像这样在 c++20 中制作一个生成器:

#include <coroutine>

template <class T>
struct generator {
    struct promise_type;
    using coro_handle = std::coroutine_handle<promise_type>;

    struct promise_type {
        T current_value;
        auto get_return_object() { return generator{coro_handle::from_promise(*this)}; }
        auto initial_suspend() { return std::suspend_always{}; }
        auto final_suspend() { return std::suspend_always{}; }
        void unhandled_exception() { std::terminate(); }
        auto yield_value(T value) {
            current_value = value;
            return std::suspend_always{};
        }
    };

    bool next() { return coro …
Run Code Online (Sandbox Code Playgroud)

c++ python yield c++20 c++-coroutine

17
推荐指数
1
解决办法
722
查看次数

标签 统计

c++ ×1

c++-coroutine ×1

c++20 ×1

python ×1

yield ×1