88
NOVEMBER 2007 | LINUX FOR YOU | www.linuxforu.com
C M Y K
Overview
his article is a follow-up to the
‘An Introduction to C++
Templates’ article published in
the October issue of LFY. So,
without further ado, let’s get
started.
Class and function templates
There are two kinds of templates: function
templates and class templates. To define a
template, use the template keyword with the
template parameters given within ankle
brackets, and provide the class or function
definition after that. For example:
// array_container is a ‘class template’
template <class T>
class array_container {
T arr[10];
// other members
};
// generic swap is a ‘function template’
template <class Type>
void swap(Type &t1, Type &t2) {
Type temp = t1;
t1 = t2;
t2 = temp;
}
The conventional names typically used for
template-type arguments are T and Type, but
it can be any valid variable name.
Template instantiation
We can ‘use’ the template by providing
necessary arguments, which is known as
instantiating the template. An instance
created from that template is a template
instantiation. For class templates, we have to
explicitly provide the instantiation arguments.
For function templates, we can explicitly
provide the template arguments or else the
T
Overview
Understanding C++
Templates
In this article, we’ll learn the basic syntax and
semantics of the features in the templates in C++ and
write small programs.
www.linuxforu.com | LINUX FOR YOU | NOVEMBER 2007
C M Y K
89
Overview
compiler will automatically infer the template arguments
from the function arguments.
For example, here is how we can instantiate the
array_container and swap templates:
// type arguments are explicitly provided
array_container<int> arr_int;
float i = 10.0, j = 20.0;
// compiler infers the type of argument as float and
// implicitly instantiates swap<float>(float &, float &);
swap(i, j);
// or explicitly provide template arguments like this:
// swap<float>(i, j);
cout<<“after swap : “<< i << “ “ << j;
// prints after swap : 20 and 10
Templa