Split it into separate prev()
and next()
functions
Is there a reason why you made next()
a template? If you would only write next<1>(...)
and next<-1>(...)
in your code, then just provide non-templated next()
and prev()
functions. This simplifies the code as well.
If you do want to keep a templated next()
, consider giving I
a default value of 1.
Consider providing an iterator-like interface instead
One issue with your code is that the caller needs to keep a raw pointer into the circular array. Instead, I would try to provide an iterator, similar to those provided by the STL containers. A simple one could be:
template <typename T, std::size_t N>
class circular_array
{
T a_[N];
public:
class forward_iterator {
circular_array& array;
std::size_t i;
public:
forward_iterator(circular_array& array): array(array) {}
T& operator*() {
return array.a_[i];
}
forward_iterator& operator++() {
++i;
if (i == N)
i = 0;
return *this;
}
};
forward_iterator begin() {
return forward_iterator(*this);
}
};
You can expand this with a reverse iterator and/or make it a bidirectional iterator with both operator++()
and operator--()
overloads, and you could even consider adding an end iterator that can never be reached. By providing enough of the standard iterator interface, it can then be used like so:
circular_array<int, 10> array = {...};
for (auto value: array | std::ranges::view::take(20)) {
std::cout << value << "\n";
}
Consider making it a view instead
Going even further, instead of starting with a circular array, you might want to have a regular array, vector or other container, fill it using the standard algorithms, and then loop over it in a circular fashion. So consider making a view that circularly loops over a given container. That way, you could write:
std::vector<int> array = {...};
for (auto value: array | circular_view() | std::ranges::view::take(20)) {
std::cout << value << "\n";
}
N
isstd::size_t
template parameter.” Of what? This code is incomplete. \$\endgroup\$next
function; noprev
function in sight, so the code is incomplete. Add the missing function, or edit the title & description. \$\endgroup\$