C++ Templates

🧩 C++ Templates – One Code, Many Types

Templates in C++ let you write code that works with any data type. It’s like saying: “Write once, reuse for int, float, or string!” 🎯

Instead of writing the same function or class over and over for different data types, you can use templates to make your code flexible and DRY (Don’t Repeat Yourself). 🧠

🛠️ Syntax of Function Template

template<typename T>
T functionName(T arg) {
    // code
}

Or you can use class instead of typename, both mean the same here.

🔧 Example: Template Function

#include <iostream>
using namespace std;

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

int main() {
    cout << "Int Add: " << add(2, 3) << endl;
    cout << "Float Add: " << add(2.5f, 3.5f) << endl;
    return 0;
}
  

Try It Now

🧱 Example: Template Class

#include <iostream>
using namespace std;

template<typename T>
class Box {
    T value;
public:
    Box(T v) : value(v) {}
    void show() {
        cout << "Value: " << value << endl;
    }
};

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

    intBox.show();
    strBox.show();

    return 0;
}
  

Try It Now

📌 Why Use Templates?

  • Reusability: One function or class for all types.
  • Type-Safe: No casting, no type confusion.
  • Generic Programming: Write more general and flexible code.

⚠️ Things to Know

  • Template functions are compiled when they’re used.
  • Errors can be tricky because they appear at compile-time.
  • Use <typename T> or <class T> — they work the same for templates.

📦 Summary

  • C++ templates allow you to write generic functions and classes.
  • Use them when the logic is the same for different data types.
  • They improve code reuse, reduce duplication, and make code easier to manage.