tags:

views:

173

answers:

3

In the code I am writing I need a foo(int, char*) and a foo(int, int) functions.

If I was coding this in C++ I would use templates. Is there any equivalent for C? Or should I use void pointers? How?

Thanks.

+10  A: 

You can't do that.
In C there are no overloads, one function, one name, you'll need to use a type that supports all your needs, e.g. (void *)

Either that or do a foo_int(int,int) and a foo_char(int, char*)

Arkaitz Jimenez
I agree. The usual C solution consists of functionnames with type suffixes. famous example: atoi, atol, atoll (IIRC) and OpenGL glVector3f, glVector2f, glColor3f, ...
dbemerlin
but if i use void* how can I then check what type the data is? there's no c isInteger and isCharPointer, right?
nunos
You can't. If you don't know what is it in advance you'll need to pass another parameter to distinguish. But thats kind of ugly, I'd implement `foo_int` and `foo_char`
Arkaitz Jimenez
+6  A: 

I think the closest you can get in C to templates is some ugly macro code. For example, to define a simple function that returns twice its argument:

#define MAKE_DOUBLER(T)  \
    T doubler_##T(T x) { \
        return 2 * x;    \
    }

MAKE_DOUBLER(int)
MAKE_DOUBLER(float)

Note that since C doesn't have function overloading, you have to play tricks with the name of the function (the above makes both doubler_int and doubler_float, and you'll have to call them that way).

printf("%d\n", doubler_int(5));
printf("%f\n", doubler_float(12.3));
Greg Hewgill
As an aside, the maintenance programmer who follows you (which may also be you) will *not* appreciate this technique. If you see a call to `doubler_int()` and don't know about the macro, how would you find that function? A search of the source code won't find it.
Greg Hewgill
+2  A: 

Others have discussed the intrinsic limitation of c with regard to overloading. Note, however, that if you can deduce which case is needed you can use varargs:

#include <stdarg.h>
foo(int, ...);

If you can't deduce it, you can pass an extra argument:

foo(int, char *spec, ...);

where spec tells the function what to expect in the subsequent arguments. Like the printf and scanf families of functions. In fact, you might find it convenient to reuse the printf/scanf conventions for specifying type, thus saving your users from having to lean another mini-language.

dmckee