C++ Tutorial – 33 – Templates I
Templates provide a way to make a class or function operate with different data types without having to rewrite the code for each type.
Function templates
The example below shows a function that swaps two integer arguments.
void swap(int& a, int& b) { int tmp = a; a = b; b = tmp; }
To convert this method into a function template that can work with any type the first step is to add a template parameter declaration before the function. This declaration includes the template keyword followed by the keyword class and the name of the template parameter, both enclosed between angle brackets. The name of the template parameter may be anything, but it is common to name it with a capital T.
template<class T>
Alternatively, the keyword typename can be used instead of class. They are both equivalent in this context.
template<typename T>
The second step in creating a function template is to replace the data type that will be made generic with the template parameter.
template<class T> void swap(T& a, T& b) { T tmp = a; a = b; b = tmp; }
Calling function templates
The function template is now complete. To use it swap can be called as if it was a regular function, but with the desired template argument specified in angle brackets before the function arguments. Behind the scenes, the compiler will instantiate a new function with this template parameter filled in, and it is this generated function that will be called from this line.
int a = 1, b = 2; swap<int>(a,b); // calls int version of swap
Every time the function template is called with a new type, the compiler will instantiate another function using the template.
bool c = true, d = false; swap<bool>(c,d); // calls bool version of swap
In this example, the swap function template may also be called without specifying the template parameter. This is because the compiler can automatically determine the type, because the function template’s arguments use the template type. However, if this was not the case, or if there is a need to force the compiler to select a specific instantiation of the function template, the template parameter would then need to be explicitly specified within angle brackets.
int e = 1, f = 2; swap(e,f); // calls int version of swap
Multiple template parameters
Templates can be defined to accept more than one template parameter by adding them between the angle brackets.
template<class T, class U> void swap(T& a, U& b) { T tmp = a; a = b; b = tmp; }
The second template parameter in the example above allows swap to be called with two arguments of different types.
int main() { int a = 1; long b = 2; swap<int, long>(a,b); }
If you like this tutorial please +1 it:


![[Affiliate link] Total Training]( http://d3qzmfcxsyv953.cloudfront.net/images/pvt-affiliates/totaltraining.png)
![[Affiliate link] Lynda](http://d3qzmfcxsyv953.cloudfront.net/images/pvt-affiliates/lynda.png)

