<template> replacement for linked list C
Just finished a small linked list in C and realized that I have a problem. There are no template arguments for C, so at the beginning of the file I declare my data type for the list, for example:
typedef int LData;
So far so good, but I can’t use this linked list for 2 (or more) different data types in one program.
I can determine LDatahow void*and manually convert it to a specific data type according to the context. But I wonder if there are more elegant solutions?
+3
5 answers
( , ), , . . , , . - , .
++, , .
// some representative bits of my linked list API
//
typedef void* PLINK;
extern PLINK LLAddToList(PLINK head, PLINK new);
extern PLINK LLNextItem(PLINK current);
// the structure I want to use it with
typedef struct _foo {
PLINK pLink;
int data1;
int data2;
} FOO;
// to allow for the link pointers to be some other than the first field
// we use this to go from link pointer to structure pointer.
FOO * FooFromPLink(PLINK current) {
return (FOO *)((char *)¤t - FIELD_OFFSET(FOO, pLink));
}
void MyFunction()
{
// this idiom to use the linklist code with a FOO struct
//
FOO * pfoo = // allocate and initialize a foo
LLAddToList(head, &pfoo->pLink);
// this idiom to traverse a list of FOOs, etc.
//
PLINK next = LLNextItem(head);
while (next)
{
pfoo = FooFromPLink(next);
// operate on foo.
next = LLNextItem(next);
}
}
0