Templates in C++ allow writing generic functions and classes, enabling code reusability for different data types.
1️⃣ Addition using Template
📌 Using a template function to add two numbers of any data type.
#include <iostream>
using namespace std;
// Template function for addition
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << "Addition of integers: " << add(10, 20) << endl;
cout << "Addition of floats: " << add(5.5, 2.3) << endl;
cout << "Addition of doubles: " << add(4.2, 3.8) << endl;
return 0;
}
🔹 Output
Addition of integers: 30
Addition of floats: 7.8
Addition of doubles: 8.0
📌 Key Points:
✔ template <typename T>
makes add(T a, T b)
work with any data type.
✔ The same function is used for int
, float
, and double
without rewriting code.
2️⃣ Data Types Example using Template
📌 Using a template class for multiple data types.
#include <iostream>
using namespace std;
// Template class
template <typename T>
class Data {
private:
T value;
public:
Data(T val) { value = val; }
void display() { cout << "Value: " << value << endl; }
};
int main() {
Data<int> obj1(100); // Integer type
Data<float> obj2(45.6); // Float type
Data<string> obj3("Hello"); // String type
obj1.display();
obj2.display();
obj3.display();
return 0;
}
🔹 Output
Value: 100
Value: 45.6
Value: Hello
📌 Key Points:
✔ template <typename T>
makes the class flexible for different data types.
✔ We created objects for int, float, and string without defining separate classes.
📌 Summary
✔ Templates enable code reusability for multiple data types.
✔ Function templates allow writing a single function for various data types.
✔ Class templates allow defining generic classes for different data types.
🚀 Want more template examples? Let me know! 🔥
0 Comments