4

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.

1
  • 1
    I would avoid the copy paste and use a generic structure. Consistency is key and less code is often better especially if it's avoiding duplicate code. Reasons for this is, readability and understanding through consistency, and fewer points of failure through less code. This also ensures that you don't make an update to one structure that you forget to add to the other structures.
    – xtratic
    Commented Nov 4, 2019 at 14:19

1 Answer 1

5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.