如何使类方法成为协程? [英] How do I make a class method a coroutine?
本文介绍了如何使类方法成为协程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使类方法成为协程?这里有一个小例子。在这里,我试图从类方法创建协程,但编译器抛出以下错误:
错误:找不到此协程的承诺类型
52|std::载体vec=co_aWait等待函数1();
如何正确设置方法的协程特征_特征?
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需要做以下修改:
您正在将错误的
Coroutine
类型作为*this
参数传递。它需要是引用:struct std::coroutine_traits<void, Coroutine&, int> {
final_suspend
必须noexcept
:std::suspend_never final_suspend() noexcept { return {}; }
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
就我从标准文本来看,这三个都是正确的错误。
这篇关于如何使类方法成为协程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文