EZ

Eduzan

Learning Hub

Eduzan
Eduzan / C++

Templates

Templates are a powerful feature in C++ that allow for generic programming. The concept behind templates is to enable functions or classes to work with any data type without rewriting code for each type. For example, a software developer may need to create a sorting function that works for various data types like integers, floating-point numbers, or characters. Instead of writing separate functions for each data type, a template can be used to write one generic function.

C++ introduces two keywords for working with templates: template and typename. The keyword typename can also be replaced with class for convenience.

How Templates Work

Templates are processed at compile time, which makes them similar to macros. However, unlike macros, templates undergo type-checking during compilation. This ensures that the code is syntactically correct for the specific data type. While the source code contains a single version of the function or class, the compiler generates multiple instances for different data types.

Function Templates

Function templates allow for the creation of generic functions that can operate on different data types. Some commonly used function templates include sort()max()min(), and printArray().

Here’s an example demonstrating a function template:

// C++ Program to demonstrate the use of templates
#include <iostream>
using namespace std;

// A function template that works for any data type
template <typename T> T getMax(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    // Calling getMax for different data types
    cout << getMax<int>(5, 10) << endl;         // int
    cout << getMax<double>(4.5, 2.3) << endl;   // double
    cout << getMax<char>('a', 'z') << endl;     // char

    return 0;
}

Output:

1.1 2.2 3.3 4.4 5.5

Multiple Template Parameters

It is possible to pass more than one type of argument to templates. This is particularly useful when you need a class or function to work with multiple types of data.

// C++ Program to demonstrate multiple template parameters
#include <iostream>
using namespace std;

template <class T1, class T2> class Pair {
    T1 first;
    T2 second;

public:
    Pair(T1 x, T2 y) : first(x), second(y) {
        cout << "Pair initialized" << endl;
    }

    void display() {
        cout << "First: " << first << ", Second: " << second << endl;
    }
};

int main() {
    Pair<int, double> p1(10, 3.14);
    p1.display();

    Pair<string, char> p2("Hello", 'A');
    p2.display();

    return 0;
}

Output:

Pair initialized
First: 10, Second: 3.14
Pair initialized
First: Hello, Second: A

Default Template Parameters

Just like regular function parameters, templates can also have default arguments. This allows for flexibility in specifying the template arguments.

// C++ Program to demonstrate default template parameters
#include <iostream>
using namespace std;

template <class T1, class T2 = int> class MyClass {
public:
    T1 data1;
    T2 data2;

    MyClass(T1 x, T2 y = 0) : data1(x), data2(y) {
        cout << "Constructor called" << endl;
    }

    void show() {
        cout << "Data1: " << data1 << ", Data2: " << data2 << endl;
    }
};

int main() {
    MyClass<double> obj1(4.5);
    obj1.show();

    MyClass<int, char> obj2(100, 'A');
    obj2.show();

    return 0;
}

Output:

Constructor called
Data1: 4.5, Data2: 0
Constructor called
Data1: 100, Data2: A
End of lesson.