I want to write a linked list that can have the data field store any build-in or user-define types. In C++ I would just use a template, but how do I accomplish this in C?
Do I have to re-write the linked list struct and a bunch of operations of it for each data type I want it to store? Unions wouldn’t work because what type can it store is predefined.
There are different approaches to this problem:
using datatype
void*: these means, you have pointers to memory locations whose type is not further specified. If you retrieve such a pointer, you can explicitly state what is inside it:*(int*)(mystruct->voidptr)tells the compiler: look at the memory locationmystruct->voidptrand interpret the contents asint.another thing can be tricky preprocessor directives. However, this is usually a very non-trivial issue:
I also found http://sglib.sourceforge.net/
Edit: For the preprocessor trick:
This would be a simple wrapper for types, but I think it can become quite complicated.