Created
August 31, 2019 07:14
-
-
Save munckymagik/a002dcace4604e70764e73a9597b34aa to your computer and use it in GitHub Desktop.
Trying out building a Range class in C++
This file contains 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
// clang++ -std=c++11 -o range range.cpp && ./range | |
// Based on http://stackoverflow.com/questions/7185437/is-there-a-range-class-in-c11-for-use-with-range-based-for-loops | |
// However https://en.wikipedia.org/wiki/Generator_%28computer_programming%29#C.2B.2B is a way simpler example | |
#include <iostream> | |
template <class T> | |
class RangeClass { | |
public: | |
class Iterator { | |
friend class RangeClass; | |
public: | |
T operator *() const { return _i; } | |
const Iterator &operator ++() { ++_i; return *this; } | |
// Iterator operator ++(int) { Iterator copy(*this); ++_i; return copy; } | |
// bool operator ==(const Iterator &other) const { return _i == other._i; } | |
bool operator !=(const Iterator &other) const { return _i != other._i; } | |
protected: | |
Iterator(T start) : _i(start) {} | |
private: | |
T _i; | |
}; | |
RangeClass(T start_value, T last_value) | |
: start_value(start_value), end_value(last_value + 1) {} | |
Iterator begin() const { return Iterator(start_value); } | |
Iterator end() const { return Iterator(end_value); } | |
private: | |
T start_value; | |
T end_value; | |
}; | |
template <class T> | |
const RangeClass<T> range(T start_value, T last_value) { | |
return RangeClass<T>(start_value, last_value); | |
} | |
int main(void) { | |
for (auto i : range(1, 8)) { | |
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