The simple answer is that you cannot do that. C was not designed for generic algorithms.
There are, however, some workarounds for particular cases.
The most common one is type-erasure, as shown in the standard library function qsort, whose prototype is:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Here the compar
function is required to take two type-erased (i.e. void
) pointers, while the array to be sorted has also been type-erased. (This means that qsort
cannot know the size of each element of the array, so you have to tell it, using the size
parameter.)
This does not let you use an arbitrary comparison function, because C does not allow you to assume that you can call func(const Type* a, const Type* b)
using the prototype func(const void* a, const void* b)
. Technically, you would need to wrap the typed comparison function with a type-erased version to allow it to be used by qsort
:
int myQsortCompare(const void* a, const void* b) {
return myCompare((const Type*)a, (const Type*)b);
}
// ...
qsort(myArray, myArraySize, sizeof *myArray, myQsortCompare);
More recent versions of the C standard allow the use of the _Generic
facility to create specific instances of a "generic" call. That can be useful under some circumstances (such as the intended use case of type-generic math functions) but it is hard to apply to a context in which an argument might be any type (or even any of a large and extensible set of types.) In particular, it doesn't provide any mechanism for the definition of a generic function.
If you tried to apply it in the qsort
case, you would need to provide a specific definition of qsort
for each value (and thus callback) type; the only benefit of the _Generic
facility is that the client could use the same syntax to call all of these diverse implementations.