<<Previous Next>>
C++ - What is function
template? - Feb 05, 2009 at 18:10 PM by Anuja
Changede
What is function
template?
Function template defines a general set of operations that will
be applied to various types of data. The type of data that the
function will operate upon is passed to it as a parameter. Through a
generic function, a single general procedure can be applied to a
wide range of data. Depending on the program, the compiler creates
different versions of function template associated with different
data types. Generic function is created using the keyword template.
It is used to create a template that describes what a function will
do. E.g. we can write a function template that swaps two numbers. We
can use the same template to swap two ints, two floats or even two
chars.
Consider following example:
#include <iostream>
template <class X> void swap(X &a, X &b)
// ? Function template {
X temp; temp = a;
a = b;
b = temp; }
int main() { int i = 10, j =
20; float x = 4.5, y =
8.7; char a = ‘A’, b =
‘B’; cout << “Original i and j are
: “<< i << ‘ ‘ << j <<
‘\n’; cout << “Original x and y
are : “<< x << ‘ ‘ << y <<
‘\n’; cout << “Original a and
b are : “<< a << ‘ ‘ << b <<
‘\n’; swap(i, j); // we can call
the same function with different
parameters swap(x, y); // Compiler has
created 3 version of template function
swap(a, b); //The correct version will be called depending
on parameters passed
cout << “Swapped i and j are : “<< i << ‘ ‘
<< j << ‘\n’; cout <<
“Swapped x and y are : “<< x << ‘ ‘ << y <<
‘\n’; cout << “Swapped a and b are
: “<< a << ‘ ‘ << b << ‘\n’;
return
0; }
Also read
What are the
syntax and semantics for a function template?
Templates is one of the features of C++. Using templates, C++
provides a support for generic programming.
We can define a template for a function that can help us create
multiple versions for different data types.....................
What is the STL, standard template
library?
The Standard Template Library, or STL, is a C++ library of
container classes, algorithms, and iterators; it provides many of
the basic algorithms and data structures................
|