【发布时间】:2015-05-19 17:42:41
【问题描述】:
如何编写泛型 c?
我开始编写一系列平衡树(替罪羊、splay、aa 等),并发现许多共同点。示例是下面的破坏函数。
这样的函数和类似的函数是否可以用 void 指针定义而不会导致“取消引用 void* 指针错误”?
销毁函数示例
void splay_node_linked_destroy(SplayNode **this) {
72 if(*this == NULL) {
73 return;
74 }
75 SplayNode *root = (*this)->root, *previous, *next;
76 while(root) {
77 if(previous == root->parent) {
78 // todo use funcs for comparisons for generic
79 if(root->left) {
80 next = root->left;
81 } else if(root->right) {
82 next = root->right;
83 } else {
84 next = root->parent;
85 }
86 } else if(previous == root->left) {
87 if(root->right) {
88 next = root->right;
89 } else {
90 next = root->parent;
91 }
92 } else {
93 next = root->parent;
94 }
95 previous = root;
96 if(next == root->parent) {
97 splay_node_destroy(&root);
98 // todo use callback here to make generic
99 }
100 root = next;
101 }
102 }
【问题讨论】:
-
一般来说,遗憾的是,答案是否定的。至少在标准 C 中,如果你不使用 UB...
标签: c generics search binary-tree binary-search-tree