r/C_Programming • • Dec 26 '22

Project Convenient Containers: A usability-oriented generic container library

https://github.com/JacksonAllan/CC
17 Upvotes

22 comments sorted by

View all comments

Show parent comment

3

u/jacksaccountonreddit Dec 30 '22 edited Dec 30 '22

There is some beauty in these hacks because underneath there is a regular C generic.

I think the most broadly useful – and least hacky – of the above hacks is the user-extendable _Generic mechanism. It could be used in many contexts, not just for containers/data structures. My first iteration of CC used only this mechanism. So it required the user to instantiate macro templates as some other libraries do…

#define VEC_NAME int_vec
#define VEC_TYPE int
#include "cc/vec.h"

… and then used the _Generic mechanism to provide a fully generic API for the generated types and functions. That approach has some notable advantages over the approach that CC now takes – it’s simpler, it relies on fewer novel tricks, the code is far easier to understand, it works with the language rather than against or around it, it doesn’t lead to a macro hellscape, etc. But it requires the user to define types, and I felt that eliminating this requirement was important to CC’s identity as the “convenient” library (in this sense, it competes with the popular stb_ds). Also, I was motivated by the recent standardization of typeof to try something that exploits it. But maybe someone else can take this technique and use it to make something like the original iteration of CC, or a generic API for an existing, more broadly scoped container library ( u/operamint ).

I believe this is a better paradigm for generic compilation than the templating model of C++ because it's layered. The type system is made to lay on top of a regular generic function rather than be a prerequisite for it.

In theory, it could be a better paradigm. But I think C++ templates still work better in practice because when you write them, you’re working with the language, using it as intended instead of fighting it at every step. Hence, other programmers can easily work with your code, rather than your code being a bit of a black box. And C++ templates, which are themselves known to be a build-speed bottleneck, compile faster (currently?) than CC containers, as I note in CC’s README:

Does it impact build times?

Yes. The compiler must do extra work deducing types, processing macros, and inlining functions at compile time. unit_tests.c, as an example of a program that uses CC extensively, compiles in 4.5 seconds in MingW with O3 in my development environment, whereas a roughly equivalent program using C++'s STL containers compiles in 3.1 seconds. So consider this point if your project is large and build speed is important.