Templates C++
Templates C++
(using C++)
Introduction
Templates are part of ANSI C++ Standard. Template is a technique that allows using a single function or class to work with different data types. A single function is created to process any type of data with in template.
Introduction contd.
The template provides generic programming by defining generic classes. In Templates, generic data types are used as arguments and
Types of Templates
Function Templates
Class Templates
Approaches for functions that implement identical tasks for different data types
Nave Approach
create unique functions with unique names for each combination of data types
Example
void PrintInt( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void PrintChar( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void PrintFloat( float x ) { To output the traced values, we insert: } PrintInt(sum); void PrintDouble( double d ) { PrintChar(initial); }
PrintFloat(angle);
char ch )
"***Debug" << endl; "Value is " << ch << endl; float x )
To output the traced values, we insert:
TemplateParamDeclaration: placeholder
Template <class SomeType> //Template declaration Class cname { // data members and member functions }
1. The first statement tells the compiler that the following function or class declaration can use the template data type. 2. Templates can not be declared inside classes or functions. 3. They must be global and should not be local.
void Print( SomeType val ) { cout << "***Debug" << endl; cout << "Value is " << val << endl; }
Template argument
The first statement tells the compiler that the following function declaration can use the template data type.
Template Functions One Function Definition (a function template) Compiler Generates Individual Functions
//Function Template
#include<iostream.h> #include<conio.h> template <class SS> void show(SS tv) { cout<<"\n Non member output:"<<tv; } void main() { clrscr(); char x='a'; int y=33; show(x); show(y); getch(); }
Class Template
A C++ language construct that allows the compiler to generate multiple versions of a class by allowing parameterized data types.
TemplateParamDeclaration: placeholder
// Class template with member function template <class T> class demo { T mem; public: demo(T tvar) { mem=tvar; } void show(T oth) void main() { { T s; clrscr(); s=oth+mem; demo <int> obj(5); cout<<endl<<"Result is :"<<s; demo <float> obj1(2.3); } obj.show(6); }; obj1.show(2);
getch();
}