OOP Template: Function and Class Template

 Function Template:

Function Templates in C++ — one of the most useful features for writing generic and reusable functions.

A Function Template allows you to write one function that works with any data type (like int, float, double, string, etc.) instead of writing separate functions for each type.

Syntax:

template <typename T>

T functionName(T a, T b) {

    // function body

}

  • template <typename T> → tells the compiler that T is a placeholder for a data type.
  • T → can be replaced with int, float, string, etc.
  • functionName → works for all types.


Example 1: Function Template for Addition

#include <iostream>
using namespace std;

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

int main() {
    cout << "Addition of integers: " << add(10, 20) << endl;
    cout << "Addition of floats: " << add(5.5, 2.3) << endl;
    cout << "Addition of strings: " << add(string("Hello "), string("World")) << endl;
    return 0;
}

Output:
Addition of integers: 30
Addition of floats: 7.8
Addition of strings: Hello World


Example 2: Function Template with Multiple Data Types
We can use more than one template parameter (e.g., T1, T2).

#include <iostream>
using namespace std;

template <class T1, class T2>
void showSum(T1 a, T2 b) {
    cout << "Sum: " << a + b << endl;
}

int main() {
    showSum(10, 20);       // int + int
    showSum(5.5, 3);       // double + int
    showSum(2.2, 3.3);     // double + double
    return 0;
}

Output:
Sum: 30
Sum: 8.5
Sum: 5.5

Class Template

A Class Template allows you to create a blueprint of a class that can work with any data type. It helps you avoid writing multiple classes for different data types.

For example, instead of writing separate classes like BoxInt, BoxFloat, etc.,

Syntax:

template <class T>

class ClassName {

    T data;      // T can be int, float, string, etc.

public:

    ClassName(T value) {

        data = value;

    }

    void display() {

        cout << data << endl;

    }

};

template <class T> → declares a template with placeholder type T.

T → can be replaced with any real data type when creating objects.

Simple Class Template

#include <iostream>

using namespace std;

template <class T>

class Box {

    T value;

public:

    Box(T v) { value = v; }


    void show() {

        cout << "Value: " << value << endl;

    }

};

int main() {

    Box<int> intBox(100);

    Box<double> doubleBox(45.67);

    Box<string> stringBox("Hello Templates!");

    intBox.show();

    doubleBox.show();

    stringBox.show();

    return 0;

}

Output:

Value: 100
Value: 45.67
Value: Hello Templates!

Post a Comment

0 Comments