use a counter

This commit is contained in:
Eric Mertens
2023-12-04 15:45:17 -08:00
parent 410790fd73
commit d66b3d3561
2 changed files with 33 additions and 3 deletions

View File

@@ -0,0 +1,30 @@
#pragma once
#include <cstdint>
#include <iterator>
template <typename T>
struct Counter
{
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
using iterator_category = std::output_iterator_tag;
struct EmptyRef {
auto operator=(T const&) const -> void { }
};
std::size_t n;
auto operator++() -> Counter& { n++; return *this; }
auto operator++(int) -> Counter { Counter temp; n++; return temp; }
auto operator*() const -> EmptyRef { return EmptyRef{}; }
auto operator-(Counter const& rhs) const -> std::ptrdiff_t {
return std::ptrdiff_t{n} - std::ptrdiff_t{rhs.n};
}
operator std::size_t() const { return n; }
};
static_assert(std::output_iterator<Counter<int>, int>);