
-----------------------------------
Clayton
Sat Oct 28, 2006 8:54 pm

[C++]Templates
-----------------------------------
Templates

What is a Template?

We have all, at some point or another, realized that some functions can do well with more than just one type (ie. adding two integers, or adding two floats/doubles, or adding (concatenating) two strings together) and for each time you wanted to do this, you would have to create a new seperate function for that type. Thankfully in C++, you have the means of ridding yourself of statically typing your functions. The means to do this is templates.

What does a template look like?

A template is really a very simple tool to use, and you will be glad that you found out about them at some point or another. Here I have a basic swap function, which takes two parameters and swaps them. Doing it the old way (ie. statically typed) i would have to create seperate functions for seperate types. Using templates however, I simply have to create one, and then at compile time, a different function is created for each type.


template 

void swap(T& a, T& b)
{
	T c = a;
	a = b;
	b = c;
}



template 


Because we are creating some new and innovative type in our program, we need to give it a name, the above simply creates a new template with the typename being T (as opposed to something like int or bool). At compile time, in one instance of a function, only one typename can be assigned to a type (ie in swap, it can only swap two ints or bools). If you wish to have more than one non-statically typed function, you must create another typename:


template 


Simple.

Some of you are probably asking what the T& part does. T is the type of the parameter being passed, and the ampersand (&) denotes a referance, meaning its value can change within the function, instead of a simple copy being used. This is much like passing a value in var format in Turing.

How do we call such a function? Easy. Simply call it with two parameters of the same type.


int my_int = 5, other_int = 7;
std::cout 