Question

I have a project that does some Dijkstra searches on a graph, I implemented a red-black tree and priority queue that I use for the nodes, however I also need the same data structures for other things such as edges. I think there will only be 2, maybe 3 types of struct I would use it with.

In such a scenario where the struct 'types' are known off top, should I use void* and pass function pointers for comparators, or would you say that duplicating the source file to maintain type safety is a stance that I can defend?

I haven't had the opportunity to delve into C enough to have an intuition on these kind of design decisions, so any help will be appreciated.

Was it helpful?

Solution

If the types that will be stored in your container are known and few in number, you can actually have both type safety and no duplication.

You start by writing a generic container, using void* to point at storage and callback functions to do stuff like comparisons. And then you write type-specific wrappers around your generic container and you use those from the rest of your code.

This becomes cumbersome if you have many wrappers to write, but two or three should be no hassle.

Licensed under: CC-BY-SA with attribution
scroll top