In the code I am writing I need foo(int, char*)
and 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?
The main type of templates that can be implemented in C are static templates.
Key differences between generics and C++ templates: Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime. The common language runtime specifically supports generics in MSIL.
Function templates. Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type.
Correct Option: C There are two types of templates. They are function template and class template.
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));
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*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With