Python 在 C/C++ 中的 yield 特性?

python's yield feature in C/C++?

本文关键字:yield 特性 中的 C++ Python      更新时间:2023-10-16

我刚刚了解了python中的yield关键字,这确实非常令人印象深刻和有用。

在C和C++语言中有对等的语言吗?

不是yield,尽管您可以使用std::iterator编写惰性迭代器(请参阅此答案)。与Python中的yield不同,您从operator++返回下一个元素。

否。

实现yield需要暂停执行,这不太适合只有一个堆栈(1)的C++模型。实现通用yield的唯一方法需要在比C++更低的级别上进行(即显式管理堆栈和执行上下文),这在C++级别上是无法实现的。

(1) C++11引入了可移植线程,这意味着可以有多个堆栈,因此可以模拟协同程序(可能效率很低):例如

#include <stdio.h>
#include <thread>
#include <mutex>
template<typename RV>
struct Generator {
    std::mutex a, b;
    bool done;
    RV *current;
    Generator() : done(false) {
        b.lock();
        std::thread([this](){ this->call_run(); }).detach();
    }
    void call_run() {
        this->run();
        done = true;
    }
    virtual void run() = 0;
    void yield(const RV & x) {
        a.lock();
        *current = x;
        b.unlock();
    }
    bool next(RV & res) {
        if (done) return false;
        current = &res;
        a.unlock();
        b.lock();
        return true;
    }
};
///////////////////////////////////////////////////////
struct Squares : Generator<int> {
    void run() override {
        for (int i=0; i<10; i++) {
            yield(i*i);
        }
    }
};
int main() {
    Squares sq;
    int x = -1;
    while(sq.next(x)) {
        printf("%in", x);
    }
    return 0;
}