Lecture #5
Function and Class Templates
In C++, templates allow you to write generic and reusable code. Both function templates and class
templates are part of this concept, which enables defining a blueprint for a function or class that works
with any data type.
Templates are the foundation of generic programming, which involves writing code in a way that is
independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library containers like
iterators and algorithms are examples of generic programming and have been developed using template
concept.
There is a single definition of each container, such as vector, but we can define many different kinds of
vectors for example, vector <int> or vector <string>.
Key Points:
Templates allow functions and classes to work with any data type.
typename or class can be used in the template definition (they are interchangeable).
The actual data type is specified when an object or function call is made.
Function templates allow functions to work with any data type.
Class templates allow classes to store and manage any type of data.
Templates enable reusability and reduce code duplication.
You can use templates to define functions as well as classes, let us see how they work.
1. Function Templates
A function template is a blueprint for creating functions. Instead of writing different versions of a
function for different data types (like int, float, etc.), you can use a single function template. function
template is also known as generic function.
Syntax
template <TypeName T>
T function Name (T arg1, T arg2) {
// function body
Note: Here, T is a placeholder for a data type that will be determined when the function is called.
2. Class Templates
A class template allows you to create a class that can handle any data type in a generic way. You can
define the data type later when creating objects of the class. Class template is also known as generic
class.
Syntax
template <typename T>
class ClassName {
T data; // 'T' will be the type of 'data'
public:
ClassName(T d) : data(d) {}
void display() {
cout << data << endl;
};