Templates — function templates, class templates
5.2.14· Coding › C++ Programming
Templates KYUN exist karte hain?
Templates ke bina tumhare paas teen bure options hain:
- Copy-paste per type → duplicated code, ek copy mein bug fix karo doosri mein nahi.
void*+ casts (purana C wala tarika) → type safety kho jaati hai, types silently mix ho sakti hain.- Macros (
#define MAX(a,b)) → koi type checking nahi, ugly double-evaluation bugs.
Templates tumhe deta hai generic code jo phir bhi compile time par fully type-checked hota hai, aur saath mein zero runtime overhead (generated code utna hi fast hota hai jitna hand-written code).
Function Templates
Kaise likhein — ek concrete function se derive karo
Ek concrete version se shuru karo:
int maximum(int a, int b) { return (a > b) ? a : b; }Generalize KYUN karein? Body mein kabhi int behaviour mention nahi hota — sirf > aur copy chahiye.
Toh type int ko ek placeholder name T se replace karo:
template<typename T> // T is a type parameter
T maximum(T a, T b) { // works for ANY T that supports >
return (a > b) ? a : b;
}Compiler KYA karta hai (instantiation)
maximum(3, 7); // T deduced as int -> generates int maximum(int,int)
maximum(2.5, 1.1); // T deduced as double -> generates double maximum(double,double)
maximum<char>('a','z'); // T explicitly charYeh step KYUN? Compiler arguments dekhta hai, T deduce karta hai, phir code generate karta hai.
Jab tak tum call nahi karte kuch exist nahi hota — ek unused template bilkul bhi machine code generate nahi karta.
Class Templates
Kaise — ek chhota generic Box banao
template<typename T>
class Box {
T value; // member of the parameter type
public:
Box(T v) : value(v) {}
T get() const { return value; }
void set(T v) { value = v; }
};<T> har jagah KYUN jahan Box ka naam ho? Functions ke unlike, class templates usually constructor se type deduce nahi kar sakte (C++17 se pehle), isliye type batani padti hai:
Box<int> bi(42); // a concrete class Box<int> is generated
Box<string> bs("hi"); // a separate class Box<string> is generatedBox<int> aur Box<string> bilkul alag types hain — runtime par koi code share nahi hota.

Non-type template parameters & default args
Ek template parameter ek compile-time value ho sakta hai, sirf type nahi:
template<typename T, int N> // N is a non-type parameter
class Array {
T data[N]; // size known at compile time -> stack-allocated
public:
int size() const { return N; }
};
Array<double, 5> a; // array of 5 doubles, N baked inKyun useful hai? N compile time par known hai → koi heap nahi, bounds check ho sakti hai, fully inlined.
Default template arguments bhi kaam karte hain: template<typename T = int> class C {...}; → C<> x;.
Template Specialization (steel-manning "one size fits all")
Kabhi-kabhi generic version ek type ke liye galat hoti hai. Specialization tumhe usse override karne deta hai:
template<typename T>
class Printer { public: void print(T x){ cout << x; } };
template<> // full specialization for bool
class Printer<bool> {
public:
void print(bool b){ cout << (b ? "true" : "false"); }
};Kyun? Generic cout << b 1/0 print karta hai; bool ke liye hum words chahte hain. Compiler sabse specialized match pick karta hai.
Flashcards
C++ mein template kya hota hai?
Template instantiation kya hai?
Template definitions header files mein KYUN rehni chahiye?
template<class T> aur template<typename T> mein kya fark hai?
maximum(3, 2.5) compile KYUN nahi hota?
Non-type template parameter kya hota hai?
int N), type nahi, e.g. Array<double,5>.Class template ko usually explicit <T> kyun chahiye lekin function template ko nahi?
Full template specialization kya hai?
template<> use karke bilkul alag implementation dena, jo us type ke use hone par choose hoti hai.Kya unused templates machine code produce karte hain?
Templates ka runtime overhead kya hai?
Recall Feynman: 12-saal ke bacche ko explain karo
Socho ek star shape wala cookie cutter. Cutter khud cookie nahi hai — woh ek shape hai. Tum usse chocolate dough, sugar dough, ya gingerbread dough mein press kar sakte ho aur har ek mein se star cookie milti hai. Template woh cookie cutter hai: woh code ki shape describe karta hai. Jab tum kehte ho "mujhe ints ka Box chahiye" ya "do doubles mein se max," compiler cutter ko us type mein press karta hai aur ek real, kaam karne wala code bake karta hai. Tumne shape ek baar likhi; computer jitne flavors chahiye utne banata hai.
Connections
- Generic Programming — templates C++ ka mechanism hai iske liye.
- STL Containers —
vector,map,pairsab class templates hain. - Function Overloading — templates vs overloads; overload resolution inke beech choose karta hai.
- Macros vs Templates — kyun templates type-safe hain aur macros nahi.
- Compile-time vs Runtime — instantiation compile time par hoti hai → zero runtime cost.
- Type Deduction (auto) —
autowahi deduction rules reuse karta hai jo function templates mein hain. - Template Specialization — specific types ke liye generic blueprint override karna.