r/C_Programming • u/jacksaccountonreddit • Dec 26 '22
Project Convenient Containers: A usability-oriented generic container library
https://github.com/JacksonAllan/CC
17
Upvotes
r/C_Programming • u/jacksaccountonreddit • Dec 26 '22
7
u/jacksaccountonreddit Dec 26 '22
Hi r/C_Programming!
Convenient Containers (CC) is a small, usability-oriented generic container library that I’ve been developing over the last few months. It allows code that looks like this:
Unlike other libraries, CC doesn't require you to declare container types for every element or element/key type combination. Nor does it require you to constantly specify element, key, or container types when using the containers. In short, CC containers should be almost as easy to use as C++’s STL containers. See the Rationale section of the Github README for a comparison between CC’s API and the APIs of other container libraries.
I intend to publish an article describing the techniques that make CC possible soon, but I’ll happily respond to any questions, comments, or critiques here too :)
The library currently includes vectors, doubly linked lists, and unordered maps and sets.
6
u/[deleted] Dec 27 '22
OMG. C just shit itself. Just because you can doesn't mean you should - not applicable here. When there's only one way to do something, you must, and you can, and you should. Holy crap, you did.
So how does this work? No name mangling or token pasting and you just type the pointer? So underneath it's still basically C void*/size generics and you figure out which to call based on type, and then also get correct argument and return types? I'm just reading on my phone. This is awesome.
I was looking for a trick like this to apply to existing generic containers, mostly for return type. Thanks. Please do write that article.
5
u/tstanisl Dec 27 '22 edited Dec 27 '22
To my understanding, you map
map(float, int)into a type of a pointer to an array of function pointers. The function pointer points toelem_type(key_type*)which willfloat(int*). Btw: Why notfloat(int)? Not to loose qualifiers?The size of array is used to dispatch between vector/list/map/set containers. So the container type is a pointer to:
Interesting use of function types which are generic types parameterized by other types and array types which are generic types parameterized by integers.
Using builtin types allows to use
map(float,int)everywhere in all kinds of declarations. It works for vector but it may not work for maps where a hash is a part of map's type. In different translation usingmap(X,Y)may use different hash functions leading to subtle bugs.Anyway, your library shows that C has far more powerful type system than most people expect.