在 C 中实现函数重载的最佳方法是什么?
What is the best method to implement function overloading in C?
我目前正在编写一个头文件 data_structures.h
,其中包含多种不同的数据结构,例如动态数组和树。我的问题是,我想要一个像 get_element()
这样的函数,它可以用动态数组或树或任何其他数据结构的实例调用。
我知道在 C 中没有函数重载这样的东西,但是有什么最佳实践方法可以解决这个问题吗?最好为每个数据结构使用另一个函数名称,例如 tree_get_element()
?
int get_element(struct dynarray *a, int index);
int get_element(struct tree *t, int index);
Would it be best to just have another function name for each data structure, for example tree_get_element()
?
是的,这是在 C 语言中的典型做法。
但如果您使用的是 C11 编译器,则可以使用泛型表达式对其进行扩展:
int dynarray_get_element(struct dynarray *a, int index);
int tree_get_element(struct tree *t, int index);
#define get_element(x, index) \
_Generic((x), \
struct dynarray *: dynarray_get_element,\
struct tree * : tree_get_element \
)((x), (index))
在 C
中有两种处理此问题的一般方法:
(1) 使用 union
和每种类型的 pointer to user-class
[您可以为每个 union member
尝试不同的字符,让函数知道您进行了哪个调用];
(2) 使用void *
作为pointer to user-class
[在这种情况下,您需要使用char *
或字符串类型来指定类型名称]。
现在,例如,(1) 将被编码为:
union _dynarrtr_ {
struct dynarray *a;
struct tree *t;
};
typedef union _dynarrtr_ UDynArrTree;
/*UATChar is either 'a' or 't' (or whichever other union members there are)*/
int get_element(char UATChar, UDynArrTree *UATPtr, int index);
并且,(2) 将编码如下:
/*Here, you can test 'typeStr' against the name of each type*/
int get_element(const char *typeStr, void *objPtr, int index);
我目前正在编写一个头文件 data_structures.h
,其中包含多种不同的数据结构,例如动态数组和树。我的问题是,我想要一个像 get_element()
这样的函数,它可以用动态数组或树或任何其他数据结构的实例调用。
我知道在 C 中没有函数重载这样的东西,但是有什么最佳实践方法可以解决这个问题吗?最好为每个数据结构使用另一个函数名称,例如 tree_get_element()
?
int get_element(struct dynarray *a, int index);
int get_element(struct tree *t, int index);
Would it be best to just have another function name for each data structure, for example
tree_get_element()
?
是的,这是在 C 语言中的典型做法。
但如果您使用的是 C11 编译器,则可以使用泛型表达式对其进行扩展:
int dynarray_get_element(struct dynarray *a, int index);
int tree_get_element(struct tree *t, int index);
#define get_element(x, index) \
_Generic((x), \
struct dynarray *: dynarray_get_element,\
struct tree * : tree_get_element \
)((x), (index))
在 C
中有两种处理此问题的一般方法:
(1) 使用 union
和每种类型的 pointer to user-class
[您可以为每个 union member
尝试不同的字符,让函数知道您进行了哪个调用];
(2) 使用void *
作为pointer to user-class
[在这种情况下,您需要使用char *
或字符串类型来指定类型名称]。
现在,例如,(1) 将被编码为:
union _dynarrtr_ {
struct dynarray *a;
struct tree *t;
};
typedef union _dynarrtr_ UDynArrTree;
/*UATChar is either 'a' or 't' (or whichever other union members there are)*/
int get_element(char UATChar, UDynArrTree *UATPtr, int index);
并且,(2) 将编码如下:
/*Here, you can test 'typeStr' against the name of each type*/
int get_element(const char *typeStr, void *objPtr, int index);