如何使 class 方法成为协程?

How do I make a class method a coroutine?

如何使 class 方法成为协程?这是一个小例子。在这里,我试图从 class 方法创建协程,但编译器抛出以下错误:

error: unable to find the promise type for this coroutine
52 | std::vector vec = co_await awaitable_func1();

如何正确设置 coroutine_traits 方法?

 auto awaitable_func1() {
        struct Awaitable {
            std::vector<int> vec;
    
            bool await_ready() { return false; }
    
            void await_suspend(std::coroutine_handle<> coroutine) {
                vec = std::vector<int>{1, 2, 3, 4, 5};
                coroutine.resume();
            }
    
            auto await_resume() {
                return vec;
            }
        };
        return Awaitable{};
    }
    
    
    class Coroutine {
    public:
        void call(int);
    };
    
    struct Promise {
        Promise(Coroutine){}
        void get_return_object() {}
    
        std::suspend_never initial_suspend() { return {}; }
    
        std::suspend_never final_suspend() { return {}; }
    
        void return_void() {}
    
        void unhandled_exception() { std::terminate(); }
    };
    
    
    template<>
    struct std::coroutine_traits<void, Coroutine, int> {
        using promise_type = Promise;
    };
    
    
    void Coroutine::call(int a) {
        std::vector<int> vec = co_await awaitable_func1();
        for (size_t i = 0; i < vec.size(); i++) {
            std::cout << vec[i] + a << std::endl;
        }
    }
    
    
    int main() {
        Coroutine a;
        a.call(5);
        return 0;
    };

抛开返回的道德规范 void,需要进行以下更改才能使 GCC 编译它:

  1. 您将错误的 Coroutine 类型作为 *this 参数传递。需要参考:

    struct std::coroutine_traits<void, Coroutine&, int> {
    
  2. final_suspend 必须是 noexcept:

    std::suspend_never final_suspend() noexcept { return {}; }
    
  3. promise 构造函数必须可以使用 0 个参数或协程的所有参数调用:

    Promise(Coroutine& this_, int& a){} // Option 1, take by value if you want to copy, use const as desired
    Promise(){} // Option 2, applicable if you don't need the parameters
    

就我从标准文本来看,这三个是正确的错误。