2

How can I code a function that accept not defined parameters ? I imagine it could work like that :

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

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

I'have read that templates could maybe solve my problem, but in C++ and I need it in C.

I'm just trying to avoid coding two functions with a lot of similar codes. In my case, I wont be looking for int or long but struct types that I defined.

Jean
  • 1,707
  • 3
  • 24
  • 43
  • 2
    You can't .... Sorry. C++ (and also C) is a typed language. – πάντα ῥεῖ Apr 08 '15 at 21:17
  • Well, you can work around of it to some extent by using a structure bundling a void pointer to **some** data and some custom type designator (as enum type, for example) – Eugene Sh. Apr 08 '15 at 21:21
  • You can have "overloaded macros" in C11 using type-generic expressions (see http://en.wikipedia.org/wiki/C11_%28C_standard_revision%29) but it might or might not be what you want. – Brian Bi Apr 08 '15 at 21:23
  • 2
    You can use a variadic function as long as you have at least one named and typed parameter -- but the type information is not passed to the function. You need a convention to specify the type (like, for example, `printf`'s format string). – Keith Thompson Apr 08 '15 at 21:23

1 Answers1

0

Since code is avoiding two functions with a lot of similar codes, write a large helper function for 2 wrapper functions (1 for each struct type).

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);
}

With C11, use of _Generic, code could get you there: Example or as commented by @Brian

Example

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
}
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256