I'm really rusty in C/C++ and was wondering how you declare a function that can take multiple data types as parameters. For instance, lets say you were making your own print function that could accept a string or an integer as an input parameter. I remember doing this in a programming class a while back but there was some way that you do the function definition so that you make two different functions, one to handle the string input and another one to handle the integer but they both have the same name.... What is that called again and is that used in C or only C++?

Thanks,
Jason O

03-13-2010

MK27

It's called a template -- you can also google "generic programming", and it is only available in C++.

Depending on exactly what you want to do, you may probably be able to do it in C using void pointers and an extra param to indicate type.

03-13-2010

grumpy

Well, no. The actual mechanism is function overloading. Declare and define two functions with the same name but different argument types.

Template functions provide one method of achieving function overloading, in the case where the definition of the function is applicable to multiple types.

Both templates and function overloading are C++ specific.

03-13-2010

MK27

Sorry, grumpy is correct. The difference between using a template and overloading a function is that without a template, the function must be defined multiple times. With a template, you can write one single function definition to cover multiple cases.