public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
}
public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法用模板技巧(或其他)在c ++中获得相同的语法?
Łuk*_*ski 26
看看boost :: Coroutine.它做你想要的. http://www.crystalclearsoftware.com/soc/coroutine/index.html#coroutine.intro
教程示例
http://www.crystalclearsoftware.com/soc/coroutine/coroutine/tutorial.html
int range_generator(generator_type::self& self, int min, int max)
{
while(min < max)
self.yield(min++);
self.exit();
}
Run Code Online (Sandbox Code Playgroud)
Mat*_* M. 10
您可以随时手动编码.说实话,yield对我来说真的好像糖涂层(以及合作例程).
那是一个协程,真的吗?一些州捆绑在一起:
在C++中,它被称为an InputIterator,并且可以任意胖.
所以,确实语法不会那么漂亮,但这应该做,只需使用标准库:
static std::array<int, 6> const Array = {{1, 2, 4, 8, 16, 16777216}};
class Integers: public std::iterator<std::input_iterator_tag,
int, ptrdiff_t, int const*, int>
{
public:
Integers(): _index(0) {}
operator bool() const { return _index < Array.size(); }
Integers& operator++() { assert(*this); ++_index; return *this; }
Integers operator++(int) { Integers tmp = *this; ++*this; return tmp; }
int operator*() const { assert(*this); return Array[_index]; }
int const* operator->() const { assert(*this); return &Array[_index]; }
private:
size_t _index;
}; // class Integers
Run Code Online (Sandbox Code Playgroud)
很明显,既然你确切地确定了存储的状态,你决定是否所有状态都是预先计算的,或者部分(或整个部分)是否被懒惰地计算,并且可能是缓存的,并且可能是多线程的,并且......你得到了想法:)
在C++ 14中,您可以这样模仿yield:
auto&& function = []() {
int i = 0;
return [=]() mutable {
int arr[] = {1,2,4,8,16,16777216};
if ( i < 6 )
return arr[i++];
return 0;
};
}();
Run Code Online (Sandbox Code Playgroud)
http://ideone.com/SQZ1qZ上提供了一个实例
协程都在C ++ 20草案和用途co_yield代替yield。
另请参阅:什么是 C++20 中的协程?
第一个链接中有一些示例用法:(第二个可能是您正在寻找的)
使用
co_await运算符暂停执行直到恢复Run Code Online (Sandbox Code Playgroud)task<> tcp_echo_server() { char data[1024]; for (;;) { size_t n = co_await socket.async_read_some(buffer(data)); co_await async_write(socket, buffer(data, n)); } }使用关键字
co_yield暂停执行返回值Run Code Online (Sandbox Code Playgroud)generator<int> iota(int n = 0) { while(true) co_yield n++; }使用关键字
co_return完成返回值的执行Run Code Online (Sandbox Code Playgroud)lazy<int> f() { co_return 7; }
| 归档时间: |
|
| 查看次数: |
19484 次 |
| 最近记录: |