Last active
January 2, 2016 18:18
-
-
Save daleobrien/8342171 to your computer and use it in GitHub Desktop.
Way to do a yield statement in C++.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
// clang++ -Wno-c++11-extensions yield.cpp;./a.out | |
class range { | |
private: | |
int last; | |
int iter; | |
bool finished; | |
public: | |
range(int end): last(end), | |
iter(0), | |
finished(false){ | |
} | |
// Iterable functions | |
const range& begin() const { return *this; } | |
const range& end() const { return *this; } | |
// Iterator functions | |
bool operator!=(const range&) const { return finished; } | |
void operator++(){ | |
if (iter >= last){ finished = true; } | |
++iter; | |
} | |
int operator*() const { return iter; } | |
}; | |
int main() { | |
for (int i: range(10)){ | |
std::cout << i << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment