Function Template:
Function Templates in C++ — one of the most useful features for writing generic and reusable functions.
A Function Template allows you to write one function that works with any data type (like int, float, double, string, etc.) instead of writing separate functions for each type.
Syntax:
template <typename T>
T functionName(T a, T b) {
// function body
}
- template <typename T> → tells the compiler that T is a placeholder for a data type.
- T → can be replaced with int, float, string, etc.
- functionName → works for all types.
T1, T2).A Class Template allows you to create a blueprint of a class that can work with any data type. It helps you avoid writing multiple classes for different data types.
For example, instead of writing separate classes like BoxInt, BoxFloat, etc.,
Syntax:
template <class T>
class ClassName {
T data; // T can be int, float, string, etc.
public:
ClassName(T value) {
data = value;
}
void display() {
cout << data << endl;
}
};
template <class T> → declares a template with placeholder type T.
T → can be replaced with any real data type when creating objects.
Simple Class Template
#include <iostream>
using namespace std;
template <class T>
class Box {
T value;
public:
Box(T v) { value = v; }
void show() {
cout << "Value: " << value << endl;
}
};
int main() {
Box<int> intBox(100);
Box<double> doubleBox(45.67);
Box<string> stringBox("Hello Templates!");
intBox.show();
doubleBox.show();
stringBox.show();
return 0;
}
0 Comments