【问题标题】:C : Function parameter with undefined type parametersC:具有未定义类型参数的函数参数
【发布时间】:2015-06-14 01:13:22
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你不能....对不起。 C++(以及 C)是一种类型化语言。
  • 好吧,你可以在某种程度上解决这个问题,方法是使用一个绑定了指向 some 数据的 void 指针和一些自定义类型指示符(例如枚举类型)的结构
  • 您可以在 C11 中使用类型泛型表达式“重载宏”(请参阅​​ en.wikipedia.org/wiki/C11_%28C_standard_revision%29),但它可能是也可能不是您想要的。
  • 您可以使用可变参数函数,只要您至少有一个命名和类型化参数——但类型信息不会传递给函数。您需要一个约定来指定类型(例如,printf 的格式字符串)。

标签: c function types parameters


【解决方案1】:

由于代码避免使用具有大量相似代码的两个函数,因此为 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
}

【讨论】:

    猜你喜欢
    • 2018-06-13
    • 2019-01-02
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2021-03-18
    相关资源
    最近更新 更多