Advantage of class templates in c++
In : IMCA Subject : Object Oriented Programming C++Advantages of Class Templates in C++
Class templates in C++ allow you to write **generic code** that works with **any data type**, without rewriting the same logic for each type.
1. **Code Reusability**
You write a class once, and it can be used with any data type (`int`, `float`, `string`, custom objects, etc.).
Example:
Instead of writing separate classes for `IntArray`, `FloatArray`, etc., you can create one `Array<T>` template class.
2. **Type Safety**
Templates ensure **type-safe operations** because the compiler checks types at compile time.
Example:
If you create a `Stack<int>`, trying to push a `string` will cause a compilation error, preventing runtime issues.
3. **Performance Efficiency**
Template code is **compiled for each type used**, so there’s no runtime overhead like with function pointers or virtual functions.
Example:
A `Vector<int>` and `Vector<double>` generate two optimized versions at compile-time — no dynamic dispatch needed.
4. **Generic Programming**
Templates enable **generic programming**, where algorithms and data structures are written independently of data types.
Example:
STL containers like `vector<T>`, `list<T>`, and `map<K,V>` use templates to work with any type.
5. **Avoids Code Duplication**
Without templates, you'd have to duplicate code for each data type, increasing maintenance effort and chances of bugs.
Example of a Class Template:
#include <iostream>
using namespace std;
template <typename T>
class Box {
T value;
public:
Box(T v) { value = v; }
T getValue() { return value; }
};
int main() {
Box<int> intBox(10);
Box<string> strBox("Hello");
cout << intBox.getValue() << endl; // Output: 10
cout << strBox.getValue() << endl; // Output: Hello
return 0;
}