Code Gre
Code Gre

Reputation: 23

C Programming template data type

I have 2 functions in C doing exactly the same thing, the only difference is the data types passed to each function e.g. one is int the other one char* . Is there a way to combine these functions to one so that when I call this one function I need not worry about the data type. This can be done in C++ using template but I want to do the same thing in C and do not know how, thx.

Upvotes: 2

Views: 2913

Answers (2)

fghj
fghj

Reputation: 9394

I know two common ways to deal with such situtation in C.
1)Replace int and "char *", with "void *p" and "int size"

void f1(int i); void f2(char *str); -> void f(void *p, int s);
f(&i, sizeof(i)); f(str, strlen(str);//or may be f(str, sizeof(str[0]);

for example see qsort from stdlib

2)Use preprocessor, like

#define f(arg) do { \
   //magic
} while (0)

things like this used to emulate std::list in linux kernel.

Upvotes: 1

Shmuel A. Kam
Shmuel A. Kam

Reputation: 84

If they are "doing exactly the same thing", then perhaps in one of them you are converting the parameter into the OTHER type (char* ==> int or int ==> char*). If so, you could do just the conversion and then call the other function. That way you'd only have one copy of the majority of it.

There is really no way to elegantly "template" behavior like that. Trying to do so, will only make your code an incomprehensible MESS.

Upvotes: 0

Related Questions