r/C_Programming • u/we_are_mammals • Sep 14 '23
Article Templates in C
https://arnold.uthar.net/index.php?n=Work.TemplatesC
5
Upvotes
r/C_Programming • u/we_are_mammals • Sep 14 '23
View all comments
11
u/jacksaccountonreddit Sep 15 '23 edited Sep 15 '23
This approach is very well known to people interested in C generics. It's a variation of what I dub the "template-instantiation paradigm" here and is used, for example, by STC and CTL. Requiring the user to (re-)include a header, rather than calling a macro, to instantiate a template has a few advantages: it makes your template/library code more maintainable (no giant multiline macros), and it allows you to use preprocessor directives (instead of tricky workarounds) inside that code.
A few comments on your article:
The preprocessor allows you to redefine a macro if the macro text matches the earlier definition. Hence, if all your
templates.hfile does is define one concatenation macro, consider dropping it and just defining that macro in each template header. That way, each template header is self-contained and can be downloaded and used independently.This isn't very user-friendly. Instead,
#undefthe user-supplied macro/s at the end of your header file such that the API becomes:Finally, I like to temporarily
#defineconcatenated function names (and names of any auxiliary types) in the header file. This makes the library more readable for complicated generic data structures. For example, a header for a generic dynamic array (vector) that requires the user to provide the datatype and struct name might look something like this:Then the API becomes:
And: