CLOSE
Updated on 17 Jun, 20256 mins read 5 views

Why Generic Programming?

In traditional programming, functions and classes are written to handle specific data types. What happens when you want the same functionality for int, float, or even a custom Point class?

You could copy-paste and rewrite code for every data type—but that's inefficient and hard to maintain. Generic Programming solves this by allowing us to write code that works for any type.

Enter: Templates.

What Are Templates?

Templates are blueprints for creating functions or classes that work with generic types. Instead of hardcoding the data type, you define a placeholder—typically called T—and let the compiler generate the appropriate code when the template is used.

Why Templates?

Consider the simple example:

int max(int a, int b) {
    return (a > b) ? a : b;
}

float max(float a, float b) {
    return (a > b) ? a : b;
}

You need to duplicate the function for different types. Templates allow you to write a single function for all data types.

Types of Templates

1 Function Templates

A function template defines a pattern for a function that can operate on generic types.

Example:

template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

Now, you can call:

int a = max(10, 20);
double b = max(3.14, 2.71);

The compiler generates the appropriate function based on the types used.

2 Class Templates

Just like functions, classes can also be made generic using class templates.

Example:

template <typename T>
class Box {
private:
    T value;
public:
    void set(T val) { value = val; }
    T get() { return value; }
};

Usage:

Box<int> intBox;
intBox.set(100);

Box<std::string> strBox;
strBox.set("Hello");