Skip to main content
1 of 2
user1095108
  • 1.4k
  • 2
  • 17
  • 29

next/prev function for a circular array

This is a next/prev function for use in a circular array. What do you think?

T a_[N];

template <std::ptrdiff_t I>
constexpr auto next(T* const p) noexcept
  requires ((1 == I) || (-1 == I))
{
  if constexpr((N & (N - 1)) && (1 == I))
    return p == &a_[N - 1] ? a_ : p + 1;
  else if constexpr((N & (N - 1)) && (-1 == I))
    return p == a_ ? &a_[N - 1] : p - 1;
  else
    return &a_[(p - a_ + I) & (N - 1)];
}

N is std::size_t template parameter.

user1095108
  • 1.4k
  • 2
  • 17
  • 29