4 Comments
User's avatar
Caden Parker's avatar

The template header approach actually seems pretty elegant. I typically program in C-style C++ and just use the occasional template. That obviously comes with the bad error messages and not great debugging info, but it's very rare that I need to make a function/type truly generic in that way.

If you needed to program in C and want actual generic types, I think the Ryan Fleury method of having a metaprogram step is probably the best way to go. Abusing the macro system can only get you so far 😅

Expand full comment
Sir Whinesalot's avatar

I thought about it and honestly it just isn't worth it to add an extra build step for this. If I'm doing something where the macro techniques aren't enough then that's a sign that C isn't a good fit for what I'm doing and I should use a fancier language instead.

Expand full comment
msa's avatar

Thank you for the informative article. I believe the "Type Erasure Idiom" should not be classified as "MEH tier". because whenever you want to achieve generics in C, you will likely use it.

Expand full comment
Sir Whinesalot's avatar

Hi msa, you're absolutely right that it is a nearly unavoidable thing. The ratings are meant more as evaluation of how nice that particular approach is to program and to use, and sadly there are lots of annoyances related to using void*.

Honestly if not for the l-value issue mentioned in the article, i.e., if I could write &42 and have it work, it would probably be bumped to a "good" just from the complete lack of macros.

I also think if C were to ever add generics to the language, the implementation should be done with type erasure. It would avoid name mangling issues (which is very important for C!) and it would work for FFI where most other languages using monomorphisation are a poor fit.

Expand full comment