我正在用纯 C 编写通用链表实现。
struct Node {
void *value;
struct Node *next;
};
struct LinkedList {
struct Node *start;
struct Node *end;
};
void LinkedList_new(struct LinkedList* llist) {
llist->start = 0;
llist->end = 0;
return;
}
void addNode( struct LinkedList *ll, void *_value ) {
if ( NULL == ll->start ) {
ll->start = (struct Node *) malloc( sizeof(struct Node) );
ll->end = ll->start;
} else {
ll->end->next = (struct Node *) malloc( sizeof(struct Node) );
ll->end = ll->end->next;
}
ll->end->value = _value;
return;
};
这一切都很好。我的问题是当我将值打印到屏幕上时。我似乎找不到打印的通用实现。
有没有办法确定分配给 void *
的 TYPE? (然后使用 switch 语句进行转换)
void printFunc(int aInt) {
char str[15];
sprintf(str, "%d", aInt);
printf(str);
}
这是一个适用于 int 的实现。我想的最坏情况是为每种类型编写不同的函数。这真的是我使用 void *
时唯一的路线吗?
有更好的方法吗?
最佳答案
不,没有办法仅从指针中得出这一点。这将需要将类型信息存储在所有运行时结构中某个明确定义的位置,这根本不是 C 使用机器的方式。
常见的解决方案是让数据类型的用户提供应用程序需要的打印功能,因为应用程序将知道存储的数据类型。也就是说,通常有一个迭代函数接受一个函数指针,在列表的每个元素上调用用户的函数(可能打印元素)。
下面是这样一个函数的样子:
void LinkedList_foreach(const LinkedList *start,
bool (*func)(void *element, void *data), void *data);
上面的代码应该为列表的每个元素调用func()
,将元素的数据和传递给用户提供的附加数据
调用者可以用来维护遍历状态的指针。回调 func()
应返回 false
以停止迭代,返回 true
以继续。
要打印一个整数,假设整数存储在指针中,您可以:
static bool print_int(void *element, void *data)
{
printf("%d\n", (int) element);
return true;
}
关于c - C中的泛型编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238185/