Macros are used for metaprogramming in C. As an example, a generic List is
typically implemented with macros, such as LIST_HEAD_INIT
in the Linux kernal
or LL_*
in (https://troydhanson.github.io/uthash/utlist.html).
I tend to dislike macros, especially ones that emulate control structures and function-macros liberally shrewn about the code. I do like the idea of C++ metaprogramming, but it can get a bit obscure.
So, how could one emulate templates in C++ to get some of the benefits, but still keep it simple so it's not so arcane?
I started with a simple linked-list. What if I could import the same file, but have it use different types?
list.c
is the start of a templated linked-list. Given a type T
, it will
generate the code to create a TListItem
and append to the list.
In the calling module, in this case main.c
you specify T
(and TListItem
)
using #define T ...
. Then, include #include "list.c"
and undefine T
.
Basically, following a lot of #define
, #include
, and #undef
, the code
itself is free from needing to use macros and instead can make real function
calls.
What do you think? Good? Bad?
$ gcc main.c
$ ./a.out
42
howdy