Templates in OOPs- Definition, Types and Example
Templates in C++
C++ Function templates are those functions which can handle different data types without separate code for each of them. Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one. Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type. C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code.
There are lot of occasions, where we might need to write the same functions for different data types. A favorite example can be addition of two variables. The variable can be integer, float or double. The requirement will be to return the corresponding return type based on the input type. If we start writing one function for each of the data type, then we will end up with 4 to 5 different functions, which can be a night mare for maintenance.
C++ templates come to our rescue in such situations. When we use C++ function templates, only one function signature needs to be created. The C++ compiler will automatically generate the required functions for handling the individual data types. This is how a programmer’s life is made a lot easier.
EXAMPLE of TEMPLATES:-
// function template
#include
using namespace std;
template
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);
n=GetMax(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
Types of TEMPLATES:-
C++ provides two kinds of templates: class templates and function templates.
• CLASS TEMPLATES
• FUNCTION TEMPLATES
Class Templates
The definition of Class Template is very similar to the Regular Class definition except it is prefixed by the Keyword Template. For example, here is the definition of a Class Template for a Stack.
Example of Class Template:-
template <class T>
class Stack
{
public:
Stack(int = 10) ;
~Stack() { delete [] stackPtr ; }
int push(const T&);
int pop(T&) ;
int isEmpty()const { return top == -1 ; }
int isFull() const { return top == size – 1 ; }
private:
int size ; // number of elements on Stack.
int top ;
T* stackPtr ;
} ;
T is a type parameter and it can be any type. For example, Stack & it Token>, where Token is a user defined class. T does not have to be a class type as implied by the keyword class. For example, Stack & lt int> and Stack & lt Message*> are valid instantiations, even though int and Message* are not “classes”.
Function Templates
The Function Template is used to perform Identical operations for type of Data compactly and Conveniently. The STL (Standard Template Library) algorithms are implemented as Function Templates. a function template represents a family of functions. For example, the C++ Standard Library contains the function template max(x, y) which returns either x or y, whichever is larger. max() could be defined like this, using the following naive template:
#include
template
const T& max(const T& x, const T& y)
{
if(y < x)
return x;
return y;
}
int main()
{
// This will call max (by argument deduction)
std::cout << max(3, 7) << std::endl;
// This will call max (by argument deduction)
std::cout << max(3.0, 7.0) << std::endl;
// This type is ambiguous; explicitly instantiate max
std::cout << max(3, 7.0) << std::endl;
return 0;
}
In the first two cases, the template argument T is automatically deduced by the compiler to be int and double, respectively. In the third case deduction fails because the type of the parameters must in general exactly match the template arguments. This function template can be instantiated with any copy-constructible type for which the expression (y < x) is valid. For user-defined types, this implies that the less-than operator must be overloaded.
Template Specialization
If we want to define a different implementation for a template when a specific type is passed as template parameter, we can declare a specialization of that template.
For example, let’s suppose that we have a very simple class called mycontainer that can store one element of any type and that it has just one member function called increase, which increases its value. But we find that when it stores an element of type char it would be more convenient to have a completely different implementation with a function member uppercase, so we decide to declare a class template specialization for that type:
// template specialization
#include
using namespace std;
// class template:
template
class mycontainer {
T element;
public:
mycontainer (T arg) {element=arg;}
T increase () {return ++element;}
};
// class template specialization:
template <>
class mycontainer {
char element;
public:
mycontainer (char arg) {element=arg;}
char uppercase ()
{
if ((element>=’a')&&(element<=’z'))
element+=’A'-’a';
return element;
}
};
int main () {
mycontainer myint (7);
mycontainer mychar (’j');
cout << myint.increase() << endl;
cout << mychar.uppercase() << endl;
return 0;
}
This is the syntax used in the class template specialization:
template <> class mycontainer { … };
Firstly we have to notice that we precede the class template name with an emptytemplate<> parameter list. This is to explicitly declare it as a template specialization.
But more important than this prefix, is the specialization parameter after the class template name. This specialization parameter itself identifies the type for which we are going to declare a template class specialization (char). Notice the differences between the generic class template and the specialization:
template class mycontainer { … };
template <> class mycontainer { … };
The first line is the generic template, and the second one is the specialization.
When we declare specializations for a template class, we must also define all its members, even those exactly equal to the generic template class, because there is no “Inheritance” of members from the generic template to the specialization.
Popularity: 1% [?]