C++ Templates | Generic Function and Class Example

C++ Templates | Generic Function and Class Example

📦 Templates in C++ – Generic Function and Class

Templates in C++ allow us to write generic and reusable code for functions and classes. This helps avoid code duplication when working with multiple data types.

📘 What Are Templates?

A template is a blueprint or formula for creating generic functions or classes. With templates, you can define a function/class once and use it with different data types without rewriting the same logic.

💡 Benefits of Using Templates

  • Code reusability
  • Type independence
  • Improved maintainability
  • Cleaner, DRY (Don't Repeat Yourself) code

🔁 Example: Generic Function and Class in C++


#include <iostream>
using namespace std;

// Generic function template
template <typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}

// Generic class template
template <class T>
class Box {
    T value;
public:
    Box(T val) : value(val) {}
    T getValue() {
        return value;
    }
};

int main() {
    // Using the function template
    cout << "Max of 5 and 9: " << getMax(5, 9) << endl;
    cout << "Max of 3.5 and 2.8: " << getMax(3.5, 2.8) << endl;

    // Using the class template
    Box<int> intBox(100);
    Box<string> strBox("Hello Templates!");

    cout << "intBox contains: " << intBox.getValue() << endl;
    cout << "strBox contains: " << strBox.getValue() << endl;

    return 0;
}
    

📝 Sample Output

Max of 5 and 9: 9
Max of 3.5 and 2.8: 3.5
intBox contains: 100
strBox contains: Hello Templates!

🔍 Explanation

  • getMax() is a generic function that compares two values of any type.
  • Box<T> is a class template that can hold any data type.
  • Templates make your code flexible and type-safe.

📌 Tips for Using Templates

  • Use <typename T> or <class T> (both are valid).
  • Templates must be fully defined in the header or the same file (not split across files like regular classes).
  • Compiler generates separate instances of the template based on usage.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences