Re:Modern programming languages require generics
by jhallenworld on Tuesday May 24, 2022 @12:04PM
(#31493828)
I've written code just like this. Another option is to make the entire sort function a C macro. This would be feasible for something simple like quicksort.
But generics provide another benefit: in theory with them, the compiler should be able to determine that two high-level types are actually the same machine type, so in the above example, SORT_ELEMENT_TYPE int and long would not generate duplicate code on many machines.
Re:Modern programming languages require generics
by KapKap55 on Tuesday May 24, 2022 @02:48PM
(#31496024)
Maybe not it, but STC (https://github.com/tylov/STC) and CTL (https://github.com/glouw/ctl) both use this define method for creating data structures and linking up compare functions for them.
Re:Modern programming languages require generics
by randbox on Tuesday May 24, 2022 @02:15PM
(#31495601)
It's not necessary to use macros. Just make both the sort function which the comparison function is passed to, as well as the comparison function itself, both "static inline". The compiler is smart enough to figure it out.
#define SORT_ELEMENT_TYPE int
#define SORT_COMPARE(a, b) sign(a - b)
#include "specialized_sort.h"
And the header would define a function with the following signature:
int sort_int(int[] a, size_t n);