
Template
A template is a simple and yet very powerful feature added in C++ Programming Language. It is a blueprint for creating a generic class or a function. Templates allow the programmer to create generic classes and generic functions and thus provides the foundation for generic programming. The idea is to pass data type as a parameter so that we do not need to write the same block of code for different data types. Templates are usually used in larger codebases to increase the reusability of the code and flexibility of the programs.
The concept of templates can be used in two different ways:
- Function Templates
- Class Templates
Function Templates
A single function template can operate with multiple data types at once but, a single normal function can only operate with one set of data types.
Usually, if you want to perform similar operations on two or more sets of data, in that case, function overloading is used to create two functions with the required function declaration and parameters.
Though, a better way would be the use of function templates because you can perform the same task with a single block of code.
- Generic functions use the idea of a function template. Generic functions specify a set of operations that can be utilized for the various types of data.
- The type of data that the function will operate on depends on the kind of data given as a parameter.
- A Generic function is formed by using the keyword template.
How to declare a function template?
It begins with the template keyword followed by template parameter/s inside < >
which then is followed by function declaration.
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Function Template to find the Largest number
// If two characters are passed to function template, character with larger ASCII value is printed.
#include <iostream>
using namespace std;
template <class T> // template function
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int num1, num2;
float fn1, fn2;
char cn1, cn2;
cout << "Enter two integers:\n";
cin >> num1 >> num2;
cout << Large(num1, num2) <<" is larger." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> fn1 >> fn2;
cout << Large(fn1, fn2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> cn1 >> cn2;
cout << Large(cn1, cn2) << " has larger ASCII value.";
return 0;
}
OUTPUT
------
Enter two integers:
5
10
10 is larger.
Enter two floating-point numbers:
12.4
10.2
12.4 is larger.
Enter two characters:
z
Z
z has larger ASCII value.
How do templates actually work?
Templates in C++ are expanded at the compiler time. This is like macros. The difference with the template is that the compiler here does type checking before template expansion.
Class Templates
Like function templates, Class templates can also be created for generic class operations.
Normally, you would build a different class for each data type or create multiple member variables and functions within a single class. This bloats your code and makes the program big unnecessarily. But sometimes, you need a class implementation that is the same for all classes, only the data types used are different.
Class templates make it easy to reuse the same block of code for multiple data types.
Syntax :
className<dataType> classObject;
Example Program:
Simple Calculator
#include <iostream>
using namespace std;
template <class T>
class Calculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
void displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
T add() { return num1 + num2; }
T subtract() { return num1 - num2; }
T multiply() { return num1 * num2; }
T divide() { return num1 / num2; }
};
int main()
{
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
cout << "Int results:" << endl;
intCalc.displayResult();
cout << endl << "Float results:" << endl;
floatCalc.displayResult();
return 0;
OUTPUT
------
Int results:
Numbers are: 2 and 1.
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Numbers are: 2.4 and 1.2.
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2
Advantages of Using Templates in C++
- They are type-safe.
- Templates help to avoid some simple errors that are found in code that make heavy use of function-like macros.
- Templates are expanded during compile time.
- They are a better way of making generalizations for APIs.
- They help to make the code short and understandable.
Disadvantages of Using Templates in C++
- All compilers do not support the nesting of templates.
- When templates are used, the whole code is exposed.
- Acts as a single point of failure.