acu*_*tea 5 c++ generator c++20
我只是一个简单的编码员,经常使用 Python 并沉迷于它的生成器。据我了解目前的情况,它们可以使用协程在 C++20 中干净地实现,但是,至少在 C++23 之前,这不是一项微不足道的任务,因为需要编写生成器类(模板)。我如何得到一个
for、ranges 库和一些等效的 Python next。如果有一种方法可以测试发电机是否已耗尽,那也很棒。这可能吗?
小智 2
正如评论中提到的,libcoro提供了更高级别的抽象,可能会解决您的一些问题。
对于第二点,如果你确实需要一个公共方法来告诉你生成器已耗尽,我想增强 libcoro 生成器会让它变得简单。这是一个(未经测试)可能的示例。但是检查 Generator.end() 对你来说有问题吗?
namespace libcoro {
template<typename T>
class [[nodiscard]] generator
{
public:
using reference_type = std::conditional_t<std::is_reference_v<T>, T, T&>;
//.. libcoro stuff
// ADDED
bool done() const {
m_coroutine.done();
}
reference_type value() const {
return m_coroutine.promise().value();
}
void resume() {
m_coroutine.resume();
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
}
然后你可以这样做:
while (true) {
gen.resume();
if(gen.done()) {
std::cout << "this is the end!" << std::endl;
break;
}
std::cout << "new value: " << gen.value() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
356 次 |
| 最近记录: |