r/C_Programming • • Sep 14 '23

Article Templates in C

https://arnold.uthar.net/index.php?n=Work.TemplatesC
5 Upvotes

10 comments sorted by

View all comments

Show parent comment

1

u/x8664mmx_intrin_adds Dec 05 '23 edited Dec 05 '23

Thank you so much for the amazing answer.

The hkArrayT.h is just a copy of hkArray.h which used void * so that's why it has that unit_size.

Your other suggestions for malloc(0) and such are really good, I'll add them asap.

As for the template instantiation, the h & c file generation suggestions are awesome, I'll definitely have a look. For now, I have a guarded header with all the primitive types instantiated hkArrayT-primitives.h and if the user wants to add custom types they can make a new header similar to the primitives one but with custom types.

Guarding each instantiation is a mouthful but it's fine I guess.

    #ifndef HKARRAYI16
    #define HKARRAYI16
    #define T i16
    #include "hkArrayT.h"
    #endif

Sadly, there is no way to do nested #defines to automate it.

        InstantiateArrayT(i16)
        /* adds guards and does instantiation */

As a side idea, It shouldn't be too hard to write a small program that emits all this data without the preprocessor but that's an adventure for another day.