我在C ++中使用什么,而不是用于co_yield函数的返回类型?<T>? C#,我可以编写以下代码: iEnumerable

问题描述 投票:0回答:1
编译器将为我生成一个类,它满足

IEnumerable<int>

接口。
现在,C ++ 20也获得了Coroutines。原则上,代码看起来非常相似:

#include <print> #include <coroutine> ??? evenUpTo(int max) { for (int i = 0; i < max; i += 2) { co_yield i; } } int main() { for (auto e : evenUpTo(11)) { std::print("{0}\n", e); } }

我将什么作为返回类型

???

我读到C ++中不需要

元,因为C ++具有迭代器。一对迭代器(
.begin()

.end()

)当然足以获得基于范围的循环工作。但是我会使用哪个容器?但是链接的问题是从2012年开始的,Coroutines来自C ++ 20,因此尚未涵盖此主题。 我可能可以编写自己的Generator<T>

模板,但是如果有内置的STL类型,我想避免。
    
C++23

C++ 23现在具有

std::generator<>

c++ c++20 c++-coroutine
1个回答
0
投票
#include <generator>

#include <print> #include <coroutine> #include <generator> std::generator<int> evenUpTo(int max) { for (int i = 0; i < max; i += 2) { co_yield i; } } int main() { for (auto e : evenUpTo(11)) { std::print("{0}\n", e); } }

Compiler Explorer:Https://godbolt.org/z/s66jbq9c7


    
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.