如何在 C 中创建通用库函数?
How to create a universal library function in C?
我想用相同的 "universal" 功能管理各种实体。这些实体被示意性地声明为:
typedef struct {
prefix_t pfx;
int i1;
int i2;
int i3;
} entity_t;
即用于内务处理的 typedef 结构前缀(包含链接指针、标志等)和有效负载。每个实体类型都有一个这样的类型声明。
管家函数只需要获取一个指向前缀的指针,这很容易,还有一个函数可以将"explore"有效载荷return一个对管家有意义的数量。
以二叉树管理为例:
void TreeInsert (prefix_t *a, prefix_t *b, int (*compare) (prefix_t *, prefix_t *));
在程序内部,我有一个这样的调用:
if (0 > compare(a, b)) {
// a comes before b
} else {
// a is the same as b or comes after
};
没关系。库函数编译没有错误也没有警告。
但是比较函数显然不能只引用前缀。它需要探测 payload 才有用:
int comp_entity (entity_t *a, entity_t *b) {
return a->i1 - b->i1;
}
编译器在以下行中针对 comp_entity 发出警告:
TreeInsert (&a->pfx, &b->pfx, comp_entity);
由于库函数用于许多不同的 "entities",比较函数不能在调用时进行类型转换。不能为前缀键入比较函数的参数,否则无法访问有效负载。
我是否应该只为了将比较传递给库函数而定义特定的函数类型?类似于:
typedef int (func_cast *) (prefix_t *, prefix_t*);
和
TreeInsert (&a->pfx, &b->pfx, (func_cast)comp_entity);
我宁愿避免这种情况。这可能吗?
备注:
我找到了 create universal function pointer to any type C language and How do I quiet the C compiler about a function pointer takes any number of arguments?,但他们没有提供解决方案。
你的比较函数知道真正的类型应该是什么,所以你会声明类型为 prefix_t *
的参数并在函数内部转换参数:
int comp_entity (prefix_t *a, prefix_t *b) {
entity_t *ea = (entity_t *)a;
entity_t *eb = (entity_t *)b;
return ea->i1 - eb->i1;
}
我想用相同的 "universal" 功能管理各种实体。这些实体被示意性地声明为:
typedef struct {
prefix_t pfx;
int i1;
int i2;
int i3;
} entity_t;
即用于内务处理的 typedef 结构前缀(包含链接指针、标志等)和有效负载。每个实体类型都有一个这样的类型声明。
管家函数只需要获取一个指向前缀的指针,这很容易,还有一个函数可以将"explore"有效载荷return一个对管家有意义的数量。
以二叉树管理为例:
void TreeInsert (prefix_t *a, prefix_t *b, int (*compare) (prefix_t *, prefix_t *));
在程序内部,我有一个这样的调用:
if (0 > compare(a, b)) {
// a comes before b
} else {
// a is the same as b or comes after
};
没关系。库函数编译没有错误也没有警告。
但是比较函数显然不能只引用前缀。它需要探测 payload 才有用:
int comp_entity (entity_t *a, entity_t *b) {
return a->i1 - b->i1;
}
编译器在以下行中针对 comp_entity 发出警告:
TreeInsert (&a->pfx, &b->pfx, comp_entity);
由于库函数用于许多不同的 "entities",比较函数不能在调用时进行类型转换。不能为前缀键入比较函数的参数,否则无法访问有效负载。
我是否应该只为了将比较传递给库函数而定义特定的函数类型?类似于:
typedef int (func_cast *) (prefix_t *, prefix_t*);
和
TreeInsert (&a->pfx, &b->pfx, (func_cast)comp_entity);
我宁愿避免这种情况。这可能吗?
备注:
我找到了 create universal function pointer to any type C language and How do I quiet the C compiler about a function pointer takes any number of arguments?,但他们没有提供解决方案。
你的比较函数知道真正的类型应该是什么,所以你会声明类型为 prefix_t *
的参数并在函数内部转换参数:
int comp_entity (prefix_t *a, prefix_t *b) {
entity_t *ea = (entity_t *)a;
entity_t *eb = (entity_t *)b;
return ea->i1 - eb->i1;
}