How to write type-safe generics in C
2025-11-15 How to write generics in C Implementing type-safe generics in C step by step C is barebones and “doesn’t support” generics, but it’s actually quite easy to implement with the tools we already have. There’s many ways you might find them being implemented in the wild. Some of the common ones are: Using function-like macros #define vector_push(vector, item) vector.buf[vector.idx++] = item; Con: This will cause everything to be inlined and loosely typed. Using void pointers void vector_push(Vector vec, void *item); Con: You rely on type erasure to achieve generics, so you’ll have to recast everything back to access them. You might also run into UB. Dispatch specializations through a function-like macro #define DECLARE_VECTOR(type) void…