Menu

1 / 2

Compile-Time Sorting in C++ With Templates: Why Heapsort Falls Apart

DEV Community·Whetlan·6 months ago
#t33Q4iTk
Reading 0:00
15s threshold

Tried implementing sorting algorithms as pure template metaprogramming. Not constexpr , not consteval . The old way, where the compiler does the sorting during template instantiation and the "output" is a type.

Quicksort worked. Mergesort worked. Heapsort turned into selection sort.

That last part took me longer to understand than I'd like to admit.

The setup

Everything operates on a type like arr<5, 3, 8, 1> . There's no runtime array. The sorted result is another type, like arr<1, 3, 5, 8> , and you verify it with static_assert .

Basic building blocks first. A typelist and element access:

template < int ... Vs > struct arr {};

template < typename Arr , int N > struct get {};

template < int A0 , int ... Args , int N > struct get < arr < A0 , Args ... > , N > { static constexpr int value = get < arr < Args ... > , N - 1 >:: value ; };

template < int A0 , int ... Args > struct get < arr < A0 , Args ...…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.