I have this function named c_sort()
that allows me to sort an array at compile-time (based on this answer):
template<typename Array>
constexpr void c_sort_impl(Array& array_) noexcept {
using size_type = typename Array::size_type;
size_type gap = array_.size();
bool swapped = false;
while ((gap > size_type{ 1 }) or swapped) {
if (gap > size_type{ 1 }) {
gap = static_cast<size_type> (gap / 1.247330950103979);
}
swapped = false;
for (size_type i = size_type{ 0 }; gap + i < static_cast<size_type> (array_.size()); ++i) {
if (array_[i] > array_[i + gap]) {
auto swap = array_[i];
array_[i] = array_[i + gap];
array_[i + gap] = swap;
swapped = true;
}
}
}
}
template<typename Array>
constexpr Array c_sort(Array array_) noexcept {
auto sorted = array_;
c_sort_impl(sorted);
return sorted;
}
This works as intended, except when I try to sort an array of function pointers in a constant expression. The problem is the line if (array_[i] > array_[i + gap])
. Pointers apparently can't be compared like this at compile-time. std::greater
doesn't seem to work either, and I can't cast the pointers to std::uint_ptr_t
because reinterpret_cast
isn't allowed in constexpr
functions.
Is there any way around this? Could a collection of pointers ever be sorted at compile-time?