Templates in C++ are used for making functions (or classes) that are defined to work for an undefined type. When the compiler sees a call to the function, it checks which types you have used in your call and makes a function definition for you. So the compiler is writing the actual function definition for you. In this way you can created several overloaded versions of a function but without having to write them all explicity.
Here is the general format of template function , varTypeName is called the template parameter.
template < typename varTypeName > type functionname ( varTypeName var1 , etc) { use varTypeName as much as you like return type; }Alternitively, you can write
template < class varTypeName > type functionname ( varTypeName var1 , etc) { use varTypeName as much as you like return type; }
Let's say you want to write a function to multiply 2 numbers, but you want to multiply either two ints or two floats or two longs etc. So you could write a whole set of overloaded functions or you can write one template function and let the compiler do the work for you. Here is how:
#include "iostream.h" template <typename var> var multiply ( var var1 , var var2) { var result; result = var1 * var2; return result; } int main() { int a=10, b=20; float c=3.5, d=5.5; a=multiply (a,b); cout<<a<<endl; c=multiply(c,d); cout<<c<<endl; c=3.5; c=multiply(c,a); cout<<c<<endl; return 1; }
In the code above, in the main() I call the function three times. First I call it with two ints then I call it with two floats. In both these cases the compiler will define the function for me. First it will define it as an int parameterized function and second as a float parameterized function. But the third call will fail. This is because I have made my template so that it only accepts two parameters of the same type. Of course they may be any type, but the two of them must be the same type. To create a template function containing two different types I would write the following code
template <typename var , typename varvar> var multiply ( var var1 , varvar var2) { var result; result = var1 * var2; return result; }
Now the main() I have written above will compile. I can now call the function in the main with any two types, even two of the same type!
template <class T>
class d : public b <T>
template <typename T>
class a : public node <typename T>
template < typename T > class base{ /* */ }; class derived : private base <derived >{ /* */ };© Nachum Danzig November 2009 - 2012