这是用 C 编写的。我有一个在许多文件中使用的句柄(我们称之为 type_handle
),目前它是一个 enum
,但目前我需要扩展它以支持 typedef-ed 结构(称为 my_type
)。由于许多函数都将 type_handle
作为输入参数,因此我不想对设计进行重大更改,从而需要重做所有文件。所以我的想法是传递int
、float
、double
,然后传递my_type
。我想要某种我想要的所有类型的 union
函数,这样我就不需要修改采用 type_handle
的函数。我应该如何设计这个?
typedef enum
{
INT = MPI_INT,
INT8 = MPI_INT8_T,
INT16 = MPI_INT16_T
}
types_t;
typedef union {
my_type dtype;
types_t etype;
} type_handle;
我想以一种方式进行设计,使得 any_func(type_handle type)
可以接受 any_func(INT)
以及 any_func(dtype)
code> 其中 dtype 是 my_type
类型的派生数据类型。
最佳答案
在 C 中使用union
时,您需要某种方法来知道要使用哪个成员。 C 本身无法告诉您 union 中的哪个元素是您分配的元素。这解释起来会很困惑,因为你已经在处理类型了,但习惯用法是:
struct {
what_is_in_the_union_t what;
union {
type_a a;
type_b b;
...
} u;
};
其中 what_is_in_the_union_t
是您自己的 { TYPE_A, TYPE_B, ... }
枚举。正如我所说,这将在您的示例中以令人困惑的方式扩展,因为您的内部 type_a
已经是 types_t
。
关于c - C 中多种数据类型的统一句柄参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093546/