Skip to content

Instantly share code, notes, and snippets.

@darvil82
Last active January 12, 2023 13:11
Show Gist options
  • Save darvil82/fa81443a787abc13c71c196f94ef9b05 to your computer and use it in GitHub Desktop.
Save darvil82/fa81443a787abc13c71c196f94ef9b05 to your computer and use it in GitHub Desktop.
A shitty constexpr range thing in C++20
// Thanks craftablescience for some improvements!
#include <cstdio>
template<typename T = int>
class Range {
template<T start, T step>
class iterator {
T current = start;
public:
constexpr const T& operator*() const { return this->current; }
constexpr T& operator*() { return this->current; }
constexpr T* operator->() { return &this->current; }
constexpr const T* operator->() const { return &this->current; }
constexpr T& operator++() {
// yes += exists, doing this so the type does not require the overload.
return this->current = this->current + step;
}
template<T start_other>
constexpr bool operator!=(const iterator<start_other, step>& other) const {
return this->current != *other;
}
};
public:
Range() = delete;
template<T start, T end_v, T step> requires (end_v >= start && step != 0)
struct between_step {
constexpr iterator<start, step> begin() { return {}; }
constexpr iterator<end_v, step> end() { return {}; }
};
template<T start, T end> using between = between_step<start, end, 1>;
template<T end> using until = between<0, end>;
};
consteval int test(){
int value = 0;
for (int i : Range<>::between<5, 10>()) {
value += i;
}
return value;
}
int main() {
int result = test();
printf("%d\n", result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment