Skip to main content
added 66 characters in body
Source Link
user1095108
  • 1.4k
  • 2
  • 17
  • 29

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

template <typename T, std::size_t N>
struct circular_array
{
  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.

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.

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

template <typename T, std::size_t N>
struct circular_array
{
  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)];
  }
};
Source Link
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.