C++ Templates: In this article, you’ll find out about templates in C++. You’ll learn to use the power of templates for generic programming.
Templates are powerful highlights of C++ which allows you to compose conventional projects. In straightforward terms, you can make a solitary capacity or a class to work with various information types using templates.
Templates are often used in a larger codebase with the end goal of code reusability and adaptability of the projects.
The idea of templates can be used in two unique manners:
• Function Templates
• Class Templates
In this article, you will learn-
- 1 Function Templates
- 2 How to declare a function template?
- 3 Example 1: Function Template to find the largest number
- 4 Example 2: Swap Data Using Function Templates
- 5 Class Templates
- 6 How to declare a class template?
- 7 How to create a class template object?
- 8 Example 3: Simple calculator using the Class template
Function Templates
A function template works in a like a normal function, with one key distinction.
A single function format can work with various information types immediately yet, a solitary ordinary capacity can just work with a lot of information types.
Ordinarily, in the event that you have to perform an indistinguishable procedure on at least two sorts of information, you use work over-burdening to make two capacities with the necessary capacity assertion.
In any case, a superior methodology is use work formats since you can play out a similar undertaking composing less and viable code.
How to declare a function template?
A function template begins with the watchword template followed by template parameter/s inside < > which is followed by work announcement.
template <class T>
T someFunction(T arg)
{
... .. ...
}
In the above code, T is a template contention that acknowledges diverse information types (int, float), and class is a catchphrase.
You can likewise use catchphrase typename rather than a class in the above example.
When an argument of a data type is passed to someFunction( ), the compiler generates a new version of someFunction() for the given data type.
Example 1: Function Template to find the largest number
Program to display largest among two numbers using function templates
// If two characters are passed to function template, character with larger ASCII value is displayed.
#include <iostream>
using namespace std;
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout << "Enter two integers:\n";
cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> c1 >> c2;
cout << Large(c1, c2) << " 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.
In the above program, a function template Large() is defined that accepts two arguments n1 and n2 of data type T. T signifies that argument can be of any data type.
The large () function returns the largest among the two arguments using a simple conditional operation.
Inside the main() function, variables of three different data types: int, float and char are declared. The variables are then passed to the Large() function template as normal functions.
During run-time, when a number is passed to the template work, the compiler realizes it needs to produce a Large() capacity to acknowledge the int contentions and does as such.
So also, when drifting point information and roast information are passed, it knows the argument data types and produces the Large() work accordingly.
Along these lines, using just a single function template supplanted three indistinguishable ordinary capacities and made your code viable.
Example 2: Swap Data Using Function Templates
Program to swap data using function templates.
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &n1, T &n2)
{
T temp;
temp = n1;
n1 = n2;
n2 = temp;
}
int main()
{
int i1 = 1, i2 = 2;
float f1 = 1.1, f2 = 2.2;
char c1 = 'a', c2 = 'b';
cout << "Before passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
Swap(i1, i2);
Swap(f1, f2);
Swap(c1, c2);
cout << "\n\nAfter passing data to function template.\n";
cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
return 0;
}
Output
Before passing data to function template.
i1 = 1
i2 = 2
f1 = 1.1
f2 = 2.2
c1 = a
c2 = b
After passing data to function template.
i1 = 2
i2 = 1
f1 = 2.2
f2 = 1.1
c1 = b
c2 = a
In this program, instead of calling a function by passing a value, a call by reference is issued.
The Swap() function template takes two arguments and swaps them by reference.
Class Templates
Like function templates, you can likewise make class formats for conventional class tasks.
Now and again, you need a class execution that is the same for all classes, just the information types used are unique.
Typically, you would need to make an alternate class for every information type OR make distinctive part factors and capacities inside a single class.
This will unnecessarily bloat your code base and will be difficult to keep up, as a change in one class/capacity ought to be performed on all classes/functions.
However, class templates make it simple to reuse a similar code for all data types.
How to declare a class template?
template <class T>
class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
In the above declaration, T is the template argument which is a placeholder for the data type used.
Inside the class body, a member variable var and a member function someOperation() are both of type T.
How to create a class template object?
To create a class template object, you need to define the data type inside a < > when creation.
className<dataType> classObject;
For example:
className<int> classObject;
className<float> classObject;
className<string> classObject;
Example 3: Simple calculator using the Class template
Program to add, subtract, multiply and divide two numbers using class template
#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
In the above program, a class template Calculator is announced.
The class contains two private members from type T: num1 and num2, and a constructor to initialize the members.
It additionally contains public part capacities to figure the option, deduction, augmentation and division of the numbers which return the estimation of information type characterized by the client. Moreover, a capacity displayResult() to show the last yield to the screen.
In the main() function, two different Calculator objects intCalc and floatCalc are created for data types: int and float respectively. The values are initialized using the constructor.
Notice we use and while creating the objects. These tell the compiler the data type used for the class creation.
This creates a class definition each for int and float, which are then used accordingly.
Then, displayResult() of both objects is called which performs the Calculator operations and displays the output.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.