【发布时间】:2016-06-14 15:01:26
【问题描述】:
我正在寻找用 C 语言创建一个函数,该函数允许我接收不同的结构类型作为参数。 例如,如果我创建 3 个不同的结构
struct a{
struct datatype0{
char test1[10];
}datatype;
struct a *next;
};
struct b{
struct datatype1{
int test1;
char test2[20];
int test3;
}datatype;
struct b *next;
};
struct c{
struct datatype2{
char test1;
char test2;
float test3;
int test4;
int test5;
}datatype;
struct c *next;
};
我想创建一个可以接收这三种不同结构之一作为参数的函数,所以我只能调用它来初始化第一种、第二种或第三种结构:
void function("---")//<-- inside the brackets i need to insert a parameter that can be struct a, or struct b or struct c.
{
//here for example I can insert the initialize function that have to work with any struct.
}
我尝试使用联合,但我看到我必须为每种结构重新创建初始化函数...我尝试使用 void 指针,但我需要在函数内部强制转换,我需要创建也为每种结构初始化函数...... 有什么想法吗??
【问题讨论】:
-
哪个 C?在 C11 中,_Generic 将允许您执行此操作。在 C89 或 C99 中,您必须自己构建调度机器
-
这样做很少是个好习惯。
-
是的,可能不要使用_Generic。您与工会走在正确的道路上。你能解释一下“必须为每种结构重新创建初始化函数”是什么意思吗?
-
等等等等! BadZen 你很好!你给了我一个主意!等一下,我测试一下!
-
@chux - 许多编译器对 C11 的支持仍然很差。我认为使用它的代码不是高度可移植的。这也不是大多数开发人员熟悉的东西。
标签: c function pointers struct unions