- In C++ a template is a simple and yet very powerful tool.
- We don’t need to write the same code for different data types because it is simple idea to pass data type as a parameter.
- Rather than maintaining and writing the multiple codes, we can write one sort () and pass data type as a parameter.
- At compiler time templates are expanded, hence this is like macros.
- At C++ there are two types of support templates, they are ‘template’ and ‘typename’.
- The difference is, the compiler does type checking before template expansion and the idea is source code contains only function/class, but compiled code may contain multiple copies of same function/class.
- Templates can be represented in two ways they are Function templates and Class templates.
Function Template
- Generic functions use the concept of function template and it defines a set of operations that can be applied to the various types of data.
- The function will operate on depends on the type of the data passed as a parameter.
- It can be implemented to an array of floats or array of integers, quick sorting algorithm is implemented using a generic function.
- Using keyword template generic function is created and template defines what function will do.
Sample Code
Output
Class Template
- Class template is also similar to function template.
- If class uses the concept of template, then the class is known as generic class.
- In class template Ttype is a placeholder name which will be determined when the class is instantiated.
- We can define one or more than generic data type using a comma-separated list. It can be used inside the class body.
Sample Code
Output