Class Templates
Class templates function templates jaisa hi concept hai, lekin poori class ke liye — generic data structures banane ke liye bahut use hota hai (jaise apna khud ka Stack, Container). C++ ki poori STL (Standard Template Library) isi concept par based hai — vector<int>, vector<string> sab ek hi generic vector template ke instances hain.
Object banate waqt actual type specify karna padta hai angle brackets mein: Box<int> ya Box<string> — compiler us specific type ke liye class generate kar deta hai.
template <typename T>
class Box {
private:
T value;
public:
Box(T v) : value(v) {}
T getValue() { return value; }
};
int main() {
Box<int> intBox(42);
Box<string> strBox("Hello");
cout << intBox.getValue() << endl; // 42
cout << strBox.getValue() << endl; // Hello
return 0;
}- Class template = generic class, kisi bhi type ke saath instantiate ho sakti hai
- Box<Type> syntax se specific type specify karo
- Puri STL (vector, map, etc.) class templates par based hai
Class templates mein default type specify kar sakte ho — agar user type na de, ek default use ho jaata hai. Ye STL containers mein bhi common hai (jaise vector ka allocator template parameter default hota hai).
template <typename T = int>
class Container {
T value;
public:
Container(T v) : value(v) {}
T get() { return value; }
};
int main() {
Container<> c1(10); // default T=int use hota hai
Container<double> c2(3.14); // explicit double
cout << c1.get() << endl; // 10
cout << c2.get() << endl; // 3.14
return 0;
}Template parameters sirf types hi nahi ho sakte — actual VALUES (jaise int) bhi ho sakte hain. Ye compile-time constants ke liye useful hai, jaise fixed-size arrays ki size template parameter se specify karna.
template <typename T, int Size>
class FixedArray {
T data[Size];
public:
int getSize() { return Size; }
};
int main() {
FixedArray<int, 5> arr; // Size = 5, compile-time constant
cout << arr.getSize() << endl; // 5
return 0;
}