c - C 中的通用列表操作函数?

标签 c list function arguments generics

什么是 C 中的通用列表操作函数? (我在浏览一些 Material 时看到了这个。)

这个函数和一个可以接受任何类型元素的函数有什么区别?

它们是一样的吗...?如果它们不相同,我们如何单独实现它们?

最佳答案

C 没有“通用”指针或对象的概念 - 最接近的是使用 void* 指针。如果您希望一段代码能够处理任何数据类型,您几乎必须使用 void* 指针。对于大小不大于指针的数据类型,您可以在类型和 void* 之间进行转换;对于较大的数据类型,您将不得不使用动态内存并让 void* 成员指向动态内存。请注意内存泄漏!

typedef struct list_node {
  struct list_node *next;
  void *data;
} list_node;

void list_insert(list_node *node, void *data) {
  // ...
}

另一方面,如果您想为每种可能的数据类型生成代码,则必须使用宏来完成,然后为您可能使用的每种数据类型实例化宏。例如:

#define DEFINE_LIST(type) \
  typedef struct list_node_##type { \
    struct list_node_##type *next; \
    type data; \
  }

#define IMPLEMENT_LIST_INSERT(type) \
  void list_##type##_insert(list_node_##type *node, type data) { \
    ... \
  }

DEFINE_LIST(int);     // defines struct list_node_int
DEFINE_LIST(double);  // defines struct list_node_double
IMPLEMENT_LIST_INSERT(int);    // defines list_int_insert
IMPLEMENT_LIST_INSERT(double); // defines list_double_insert

关于c - C 中的通用列表操作函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/326202/

相关文章:

postgresql - 调用一个函数,该函数具有分配给它的数值以进行查询

c - 在重定向输入期间,在没有 SIGINT 的情况下,在 C 中使用键盘停止 unix 程序

c - scanf 函数内的空白 - C 编程

list - 如何将公告列表/Web 部件添加到发布门户

c# - List<> 内的 "Tag"字符串

php - WordPress Mobile Detect 作为 body_class 函数

c - 为什么这些指针显示不同的地址?

c - 测量 cortex m7 上的时钟周期计数

c - 列表上的简单 merge_sort - 分析

javascript - js创建高级原型(prototype)