Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent in C for C++ templates?

Tags:

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?

like image 813
nunos Avatar asked May 20 '10 12:05

nunos


People also ask

Is there templates in C?

The main type of templates that can be implemented in C are static templates.

Is generic same as template in C++?

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.

What is function template C?

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.

How many templates are there in C?

Correct Option: C There are two types of templates. They are function template and class template.


2 Answers

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)); 
like image 197
Greg Hewgill Avatar answered Sep 28 '22 03:09

Greg Hewgill


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*)

like image 42
Arkaitz Jimenez Avatar answered Sep 28 '22 04:09

Arkaitz Jimenez