C++ 如何使类方法成为协同程序?
如何使类方法成为协同程序?这里有一个小例子。在这里,我试图从类方法创建一个协程,但编译器抛出以下错误: 错误:找不到此协同程序的承诺类型C++ 如何使类方法成为协同程序?,c++,asynchronous,c++20,c++-coroutine,C++,Asynchronous,C++20,C++ Coroutine,如何使类方法成为协同程序?这里有一个小例子。在这里,我试图从类方法创建一个协程,但编译器抛出以下错误: 错误:找不到此协同程序的承诺类型 52 | std::vector vec=co_wait waitable_func1() 如何为方法正确设置协同程序 auto awaitable_func1() { struct Awaitable { std::vector<int> vec; bool await_
52 | std::vector vec=co_wait waitable_func1() 如何为方法正确设置协同程序
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;
};
自动等待功能1(){
结构等待{
std::vec;
bool wait_ready(){return false;}
void wait\u suspend(标准::协程\句柄协程){
vec=std::向量{1,2,3,4,5};
coroutine.resume();
}
自动等待恢复(){
返回向量;
}
};
等待返回{};
}
类协程{
公众:
无效通知(int);
};
结构承诺{
允诺(协同程序){}
void get_return_object(){}
std::suspend_never initial_suspend(){return{};}
std::suspend_never final_suspend(){return{};}
void return_void(){}
无效未处理的_异常(){std::terminate();}
};
模板
struct std::coroutine_traits{
使用承诺类型=承诺;
};
void协同程序::调用(int a){
std::vector vec=co_wait waitable_func1();
对于(size_t i=0;i std::cout抛开返回void
的道德规范不谈,需要进行以下更改才能使GCC编译此文件:
您将错误的Coroutine
类型作为*此
参数传递。它需要是一个引用:
struct std::coroutine_traits<void, Coroutine&, int> {
承诺构造函数必须可使用0个参数或协同例程的所有参数进行invocable:
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
从标准文本中我可以看出,这三个错误是正确的。协同程序返回void
是没有意义的。
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