Writing Type-Safe Generics in C
-
Writing Type-Safe Generics in C
The fun part about a programming language like C is that although the language doesn’t directly support many features including object-oriented programming and generics, there’s nothing that’s keeping you from implementing said features in C. This extends to something like type-safe generics in C, as [Raph] demonstrates in a blog post.
After running through the various ways that generics are also being implemented using methods including basic preprocessor macros and void pointers, the demonstrated method is introduced. While not necessarily a new one, the advantage with this method is that is type-safe. Much like C++ templates, these generics are evaluated at compile time, with the preprocessor handling both the type checking and filling in of the right template snippets.
While somewhat verbose, it can be condensed into a single header file, doesn’t rely on the void type or pointers and can be deduplicated by the linker, preventing bloat. If generics is what you are looking for in your C project, this might be a conceivable solution.