Templates

Templates, Templates, Templates. A template is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A template negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

The syntax for a template is

template <class (template variable name) > (return type) function name (parameters)

Hopefully the code will help in the explanation.

#include <iostream>
 
// the definition is similar to a function, (return type) (function name) (parameters...) instead
// it has a template <class (name of template)>
template <class T> T TemplateAdd(T a, T b)
{
              return (a+b);              // use the internal adding for the variable of type T
              // e.g if defined as a int, then use int add internal, or if a double, use a double etc.
}
 
// template class, same as a function apart from a class 
template<class T> class TemplateClass
{
private:
       T value;       // the internal value
public : 
       TemplateClass(T va)       // set the default internal value in the constructor
       {
              value = va;
       }
 
       T ReturnValue()              // return the default value, all using the template class
       {
              return value;
       }
};
 
int main()
{
       // standard template for a function, pass in two integer values, and also two doubles, it will both work the same
       std::cout << "Adding " << TemplateAdd(3,1) << " " <<  TemplateAdd(3.4, 5.4) << "\n";
 
       // create a int class with the default value of 3
       TemplateClass<int> intTemplate(3);
       std::cout << intTemplate.ReturnValue() << "\n";
 
       // using the same constructor, create a char class with the default value 'b'
       TemplateClass<char> charTemplate('b');
       std::cout << charTemplate.ReturnValue() << "\n";
 
       return 0;
}

Save as templates.cpp, then compile the program. The result displayed will be
Adding 4 8.8
3
b

So using the templates will cut down on the standard function/class types but you do need to be careful to not use any of the non internal class calls within the template, e.g. if you create a new type and do not proved a function to increment the values this will not work.

Just a note that you could add in more different types of templates by
template (return value) (function name) (parameters , e.g. S input1, T input2)

Leave a Reply

Your email address will not be published. Required fields are marked *