PDFVersion
No ads? No problem! Download the PDF book of this tutorial for just $24.99. Your support will help us reach more readers.
Thank You!
TEMPLATES:
C++ boasts a dominant feature known as templates, enabling generic programming. Templates serve as blueprints for creating generic functions or classes, promoting generalized structures over specialized ones. This programming paradigm facilitates the use of various data types within a program by defining a single class or function. Consequently, emphasis is placed on the logic and quality of programming. Referring to C++ Templates as generic classes, they prove invaluable in larger projects by enhancing program flexibility and reusability.
Consider a scenario where we've developed a simple program named "Calculator," capable of performing arithmetic operations on integers. While functional, what if we require similar operations on floating-point numbers? Would we need to develop a separate program? Indeed, without C++'s template feature, separate implementations would be necessary for each data type. Templates streamline this process, significantly simplifying our programming tasks.
There are two primary types of templates in C++:
Creating a class template is straightforward and serves the purpose of generating a generic class capable of handling different data types. Without templates, managing numerous classes for various data types becomes cumbersome. Class templates alleviate this burden by enabling code reuse across different data types.
Declaration of Class Template:template <class T>
class className {
public:
T number;
T Method();
};
In the above syntax:
- templatedeclares the template class.
- classdenotes the class template.
- Tacts as a placeholder for the data type.
- classNamerepresents the template class name.
Since it's a generic class, specifying the data type for each object is necessary for reusability. The basic syntax for creating an object of a template class is:
className<Data-type> class-object;
In the above syntax:
- classNameis the template class name.
- Data-typecan be any valid data type.
- class-objectrepresents the object of the template class.
Consider the following example to illustrate creating objects of a template class for different data types:
className<int> classObject;
className<string> classObject;
className<float> classObject;
Now, let's dive into a quick example to understand class templates better: We'll create a straightforward Calculator Program using a class template.
#include <iostream>
using namespace std;
template <class T> // Template class
class Calculator {
private:
T var1, var2; // Variables of type "T"
public:
// Constructor with arguments of type "T"
Calculator(T num1, T num2) {
var1 = num1;
var2 = num2;
}
// Method to display result on the screen
void showResult() {
cout << "\n Addition: " << var1 << " + " << var2
<< " = " << add() << endl;
cout << " Subtraction: " << var1 << " - " << var2
<< " = " << sub() << endl;
cout << " Multiplication: " << var1 << " x " << var2
<< " = " << multi() << endl;
cout << " Division: " << var1 << " / " << var2
<< " = " << divid() << endl;
cout << "==================================" << endl;
}
// Methods of type T: return the result
T add() { return var1 + var2; }
T sub() { return var1 - var2; }
T multi() { return var1 * var2; }
T divid() { return var1 / var2; }
};
int main() {
Calculator<int> intCalc(2, 1);
Calculator<float> floatCalc(2.4, 1.2);
cout << "TEMPLATE CLASS FOR INTEGERS:" << endl;
intCalc.showResult();
cout << endl << "TEMPLATE CLASS FOR FLOAT:" << endl;
floatCalc.showResult();
return 0;
}
In this example, we've defined a class template named Calculator
, with two private member variables of type T
. The class has methods for addition, subtraction, multiplication, and division, with results corresponding to the user-defined data types such as int
and float
. Objects of the class are created with specific data types, utilizing constructors to assign values.
In a template class, the code for specifying the data type is written once before the class definition; repeating it before each function implementation is incorrect.
Function templates behave similarly to regular functions but offer versatility in handling multiple data types within a single function. Like class templates, function templates promote code reuse and minimize programming efforts and maintenance.
Declaration of Function Templates:template <class T>
T function_Name(T argument_list) {
// Body of the function
}
In the above syntax:
- templatedeclares the template function.
- classis used to indicate a class template, but typename can also be employed interchangeably.
- Tserves as a placeholder for the data type used by the function.
Let's consider an example to understand how to create and utilize a template function in C++:
#include <iostream>
using namespace std;
template <class T>
// Swap function: arguments passed by reference
void Swap(T &var1, T &var2) {
T temp; // Temporary variable of type "T"
temp = var1;
var1 = var2;
var2 = temp;
}
int main() {
int int1 = 5, int2 = 10;
float float1 = 5.1, float2 = 10.5;
char char1 = 'a', char2 = 'b';
cout << "Before using the function template.\n";
cout << "int1 = " << int1 << "\nint2 = "
<< int2;
cout << "\nfloat1 = " << float1 << "\nfloat2 = "
<< float2;
cout << "\nchar1 = " << char1 << "\nchar2 = "
<< char2;
Swap(int1, int2);
Swap(float1, float2);
Swap(char1, char2);
cout << "\n================================" << endl;
cout << "After passing data to function template.\n";
cout << "int1 = " << int1 << "\nint2 = " << int2;
cout << "\nfloat1 = " << float1 << "\nfloat2 = "
<< float2;
cout << "\nchar1 = " << char1 << "\nchar2 = "
<< char2;
return 0;
}
In the above example, we call the Swap
function by passing references to swap variables.
A template serves as a pattern. Just as some word processing programs offer built-in templates for resumes and business letters, templates in programming enable code reuse and flexibility across various data types.
Sardar Omar
I did my hardest to present you with all of the information you need on this subject in a simple and understandable manner. However, if you have any difficulties understanding this concept or have any questions, please do not hesitate to ask. I'll try my best to meet your requirements.