Templates in C++

By Shakib Ansari | Date: Mon, Jun 2, 2025

C++ mein Templates ek powerful feature hai jo hume generic code likhne ki ability deta hai, yaani ek hi function ya class ko multiple data types ke saath use kar sakte hain bina baar-baar likhe.

Templates ka use hota hai code reusability aur type safety maintain karne ke liye.

1. Function Templates

Function templates aise functions hote hain jo multiple data types ke liye kaam karte hain, using a placeholder type.

Syntax:

template <typename T>
T add(T a, T b) {
    return a + b;
}

Example:

#include <iostream>
using namespace std;

template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    cout << "Int: " << add(5, 10) << endl;
    cout << "Float: " << add(5.5f, 3.3f) << endl;
    return 0;
}

Output:

Int: 15
Float: 8.8

2. Class Templates

Agar aap ek class create kar rahe ho jo different data types handle kare jaise Stack, Queue, etc to class templates ka use hota hai.

Syntax:

cpp
CopyEdit
template <class T>
class Box {
    T value;
public:
    Box(T val) : value(val) {}
    void display() {
        cout << "Value: " << value << endl;
    }
};

Example:

int main() {
    Box<int> intBox(100);
    Box<string> strBox("Hello");

    intBox.display();   // Output: Value: 100
    strBox.display();   // Output: Value: Hello
    return 0;
}

3. Use Cases of Generic Programming

Generic programming ka matlab hota hai ek hi logic ko multiple types ke liye likhna.

Real-world use cases:

  • Sorting algorithms (int, float, string)
  • Generic containers (like vector, stack, queue in STL)
  • Mathematical operations on different numeric types
  • Reusable utility functions (min, max, swap)

Why Use Templates?

  1. Code Reusability: Ek hi code har type ke liye chalega.
  2. Type Safety: Compile-time checking hoti hai.
  3. Performance: Runtime overhead nahi hota.

Bonus Tip: Multiple Template Parameters

template <typename T1, typename T2>
class Pair {
    T1 x;
    T2 y;
public:
    Pair(T1 a, T2 b) : x(a), y(b) {}
    void show() {
        cout << "First: " << x << ", Second: " << y << endl;
    }
};

int main() {
    Pair<int, string> p(1, "Shakib");
    p.show();
    return 0;
}

📌 Output:

First: 1, Second: Shakib
About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments