PREV NEXT
What are Templates?
- Template is an important and powerful feature in C++. It is used to pass the data type as a parameter so that you don’t need to write same code for different data types.
- It allows you to define the generic classes and generic functions and thus provides support for generic programming.
- For example if you need to sort( ) for different data type rather than writing and maintaining the multiple codes you can write one sort( ) and pass data type as a parameter.
How Templates work?
- The templates are expanded at the compiler time and they are like macros. The difference is that compiler does type checking before template expansion.
- The source code contains only function or class but compiled code may contain multiple copies of same function or class.
Types of Template
Let us discuss these two in details:
Function Templates:
The function template can work with different data types at once. The concept of function template is used by generic functions and it defines a set of operations that can be applied to the various types of data. The type of the data that the function will operate on depends on the type of the data passed as a parameter. Syntax of function template:
1 2 3 4 5 6 7 |
template<class Ttype> ret_type_func_name(parameter_list) { //body of function } |
Let us have a look at the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> using namespace std; template<class Sum> Sum add(Sum &a,Sum &b) { Sum result = a+b; return result; } int main() { int x =6; int y =3; cout<<"Addition of i and j is :"<<add(x,y); cout<<'\n'; return 0; } |
Class Templates:
- The class templates can be defined in the same way as functions are defined and when the class uses the concept of template then that class is known as generic class.
- The class template can be useful for classes like linked list, stack, array, etc.
Syntax of class template:
1 2 3 4 5 6 7 8 9 10 11 |
template<class type> class class-name { . . . } |
Let us have a look at the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
#include <iostream> using namespace std; template <typename T> class ArrTest { private: T *ptr; int size; public: ArrTest(T arr[], int s); void print(); }; template <typename T> ArrTest<T>::ArrTest(T arr[], int s) { ptr = new T[s]; size = s; for(int i = 0; i < size; i++) ptr[i] = arr[i]; } template <typename T> void ArrTest<T>::print() { for (int i = 0; i < size; i++) cout<<" "<<*(ptr + i); cout<<endl; } int main() { int arr[5] = {6, 2, 3, 7, 1}; ArrTest<int> a(arr, 5); a.print(); return 0; } |