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
就我从标准文本来看,这三个都是正确的错误。
这篇关于如何使类方法成为协程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何使类方法成为协程?


基础教程推荐
猜你喜欢
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05