gpt4 book ai didi

C : Function parameter with undefined type parameters

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:35 30 4
gpt4 key购买 nike

如何编写接受未定义参数的函数?我想它可以像那样工作:

void foo(void undefined_param)
{
if(typeof(undefined_param) == int) {/...do something}

else if(typeof(undefined_param) == long) {/...do something else}
}

我读过模板也许可以解决我的问题,但在 C++ 中,我需要在 C 中使用它。

我只是想避免用大量相似的代码编写两个函数。就我而言,我不会寻找 intlong,而是寻找我定义的结构类型。

最佳答案

由于代码避免了两个具有大量相似代码的函数,因此为 2 个包装函数(每种结构类型 1 个)编写一个大型辅助函数。

struct type1 {
int i;
};

struct type2 {
long l;
};

static int foo_void(void *data, int type) {
printf("%d\n", type);
// lots of code
}

int foo_struct1(struct type1 *data) {
return foo_void(data, 1);
}

int foo_struct2(struct type2 *data) {
return foo_void(data, 2);
}

对于 C11,使用 _Generic,代码可以让您到达那里:Example或由 @Brian 评论

例子

int foo_default(void *data) {
return foo_void(data, 0);
}

#define foo(x) _Generic((x), \
struct type1*: foo_struct1, \
struct type2*: foo_struct2, \
default: foo_default \
)(x)

void test(void) {
struct type1 v1;
struct type2 v2;
foo(&v1); // prints 1
foo(&v2); // prints 2
}

关于C : Function parameter with undefined type parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29525489/

30 4 0