Is there an equivalent in C for C++ templates?
Yes, there is. You can use type-generic expression in C11:
#include <stdio.h>
void foo_char_ptr(int a, char *b) {
printf("Called int, char*.\n");
}
void foo_int(int a, int b) {
printf("Called int, int.\n");
}
#define foo(a, b) _Generic((b), char*: foo_char_ptr, int: foo_int)(a, b)
int main() {
foo(1, 1);
foo(1, "foo");
}
// Output:
// Called int, int.
// Called int, char*.
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));