Function Templates
Bina templates ke, agar tumhe max() function chahiye int ke liye aur double ke liye dono, do alag overloaded functions likhne padte (function overloading se). Templates se ek hi generic function likh sakte ho jo kisi bhi type ke saath kaam kare — compiler automatically sahi version generate kar deta hai jab call hota hai.
template <typename T> syntax se generic function define karte hain — T ek placeholder hai jo actual type se replace ho jaata hai compile-time par (isse "compile-time polymorphism" bhi kehte hain).
template <typename T>
T maxVal(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << maxVal(5, 10) << endl; // T = int
cout << maxVal(3.5, 2.1) << endl; // T = double
cout << maxVal('a', 'z') << endl; // T = char
return 0;
}- template <typename T> = generic function, kisi bhi type ke liye
- Compiler compile-time par sahi type ka version generate karta hai
- Code duplication (multiple overloads) avoid karne ka powerful tareeka
Template mein ek se zyada type parameters bhi ho sakte hain — jaise ek function jo do ALAG types leta ho aur unhe combine kare, ya ek pair jaisi cheez banaye.
template <typename T1, typename T2>
void printPair(T1 a, T2 b) {
cout << a << " and " << b << endl;
}
int main() {
printPair(5, "hello"); // T1=int, T2=const char*
printPair(3.14, 'x'); // T1=double, T2=char
return 0;
}Kabhi-kabhi ek specific type ke liye generic template ka behavior alag chahiye hota hai — "template specialization" se us specific type ke liye custom implementation likh sakte ho, baaki types generic version use karte rahenge.
template <typename T>
void printType(T val) {
cout << "Generic: " << val << endl;
}
template <> // specialization for char*
void printType(const char* val) {
cout << "String: " << val << endl;
}
int main() {
printType(42); // "Generic: 42"
printType("Hello"); // "String: Hello" — specialized version chala
return 0;
}