5.2.14 · HinglishC++ Programming

Templates — function templates, class templates

1,798 words8 min readRead in English

5.2.14 · Coding › C++ Programming


Templates KYUN exist karte hain?

Templates ke bina tumhare paas teen bure options hain:

  1. Copy-paste per type → duplicated code, ek copy mein bug fix karo doosri mein nahi.
  2. void* + casts (purana C wala tarika) → type safety kho jaati hai, types silently mix ho sakti hain.
  3. 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 char

Yeh 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 generated

Box<int> aur Box<string> bilkul alag types hain — runtime par koi code share nahi hota.


Figure — Templates — function templates, class templates

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 in

Kyun 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?
Ek blueprint jo type(s)/value(s) se parameterized hota hai jisse compiler concrete functions ya classes generate karta hai (instantiation).
Template instantiation kya hai?
Compiler ka ek specific type ke liye actual code generate karna jab template us type ke saath use ho.
Template definitions header files mein KYUN rehni chahiye?
Kyunki instantiation ko use ke point par poori body chahiye, jo doosre translation units mein hoti hai; ek .cpp body unhe visible nahi hoti → linker error.
template<class T> aur template<typename T> mein kya fark hai?
Type parameters ke liye koi fark nahi — fully interchangeable.
maximum(3, 2.5) compile KYUN nahi hota?
T pehle arg se int aur doosre se double deduce hota hai → conflicting deductions; compiler ek T choose nahi kar sakta.
Non-type template parameter kya hota hai?
Ek template parameter jo compile-time value hota hai (jaise int N), type nahi, e.g. Array<double,5>.
Class template ko usually explicit <T> kyun chahiye lekin function template ko nahi?
Function templates argument types se T deduce karte hain; class templates (C++17 se pehle) constructor se deduce nahi kar sakte, isliye type specify karni padti hai.
Full template specialization kya hai?
Ek specific type ke liye 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?
Nahi — code sirf actually use hone wali instantiations ke liye generate hota hai.
Templates ka runtime overhead kya hai?
Zero — generated code hand-written type-specific code ke equivalent hota 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 Containersvector, map, pair sab 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)auto wahi deduction rules reuse karta hai jo function templates mein hain.
  • Template Specialization — specific types ke liye generic blueprint override karna.

Concept Map

bad options

problems

write algorithm once

keyword

type-safe, zero runtime cost

family of functions

family of classes

compiler deduces T

used in STL

conflicting arg types

fix

Repeated logic per type

Copy-paste, void*, macros

Templates

Blueprint parameterized by type

template typename T

Generic + fast code

Function template

Class template

Instantiation

vector, pair, map

Deduction ambiguity

Explicit T or two params