Last active
December 8, 2015 06:16
-
-
Save minjang/12df1b138d30a28b6703 to your computer and use it in GitHub Desktop.
Python-like range implementation with C++11
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
#include <iostream> | |
template<typename T> | |
class range_iterator { | |
T cur_; | |
const T step_ = 1; | |
public: | |
range_iterator(T init) : cur_{init} {} | |
range_iterator& operator++() { | |
cur_ += step_; | |
return *this; | |
} | |
bool operator!=(const range_iterator<T> &rhs) const { | |
return cur_ != rhs.cur_; | |
} | |
T operator*() const { | |
return cur_; | |
} | |
}; | |
template<typename T> | |
class range_impl { | |
const T start_; | |
const T stop_; | |
public: | |
range_impl(T start, T stop) : | |
start_{start}, stop_{stop} {} | |
range_iterator<T> begin() const { | |
return range_iterator<T>{start_}; | |
} | |
range_iterator<T> end() const { | |
return range_iterator<T>{stop_}; | |
} | |
}; | |
template<typename T> | |
range_impl<T> range(const T start, const T stop) { | |
return range_impl<T>{start, stop}; | |
} | |
int main() { | |
for (int i : range(1, 4)) | |
std::cout << i << "\n"; | |
for (double i : range(7.5, 10.5)) | |
std::cout << i << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment