TEMPLATES:


C++ boasts a dominant feature known as templates, enabling generic programming. Templates serve as blueprints for creating generic functions or classes, promoting generalized structures over specialized ones. This programming paradigm facilitates the use of various data types within a program by defining a single class or function. Consequently, emphasis is placed on the logic and quality of programming. Referring to C++ Templates as generic classes, they prove invaluable in larger projects by enhancing program flexibility and reusability.

Consider a scenario where we've developed a simple program named "Calculator," capable of performing arithmetic operations on integers. While functional, what if we require similar operations on floating-point numbers? Would we need to develop a separate program? Indeed, without C++'s template feature, separate implementations would be necessary for each data type. Templates streamline this process, significantly simplifying our programming tasks.

There are two primary types of templates in C++:

Creating a class template is straightforward and serves the purpose of generating a generic class capable of handling different data types. Without templates, managing numerous classes for various data types becomes cumbersome. Class templates alleviate this burden by enabling code reuse across different data types.

Declaration of Class Template:
template <class T> 
class className {
    public:
        T number;
        T Method();
};

In the above syntax:

  • templatedeclares the template class.
  • classdenotes the class template.
  • Tacts as a placeholder for the data type.
  • classNamerepresents the template class name.

Since it's a generic class, specifying the data type for each object is necessary for reusability. The basic syntax for creating an object of a template class is:

className<Data-type> class-object;

In the above syntax:

  • classNameis the template class name.
  • Data-typecan be any valid data type.
  • class-objectrepresents the object of the template class.

Consider the following example to illustrate creating objects of a template class for different data types:

className<int> classObject; 
className<string> classObject;
className<float> classObject;

Now, let's dive into a quick example to understand class templates better: We'll create a straightforward Calculator Program using a class template.

CLASS TEMPLATE - C++ Copy to Clipboard  
#include <iostream>
using namespace std;

template <class T> // Template class
class Calculator {
    private:
        T var1, var2; // Variables of type "T"

    public:
        // Constructor with arguments of type "T"
        Calculator(T num1, T num2) { 
            var1 = num1;
            var2 = num2;
        }

        // Method to display result on the screen
        void showResult() { 
            cout << "\n Addition: " << var1 << " + " << var2 
                 << " = " << add() << endl;
            cout << " Subtraction: " << var1 << " - " << var2 
                 << " = " << sub() << endl;
            cout << " Multiplication: " << var1 << " x " << var2 
                 << " = " << multi() << endl;
            cout << " Division: " << var1 << " / " << var2 
                 << " = " << divid() << endl;
            cout << "==================================" << endl;
        }

        // Methods of type T: return the result
        T add() { return var1 + var2; }
        T sub() { return var1 - var2; }
        T multi() { return var1 * var2; }
        T divid() { return var1 / var2; }
};

int main() {
    Calculator<int> intCalc(2, 1);
    Calculator<float> floatCalc(2.4, 1.2);

    cout << "TEMPLATE CLASS FOR INTEGERS:" << endl;
    intCalc.showResult();

    cout << endl << "TEMPLATE CLASS FOR FLOAT:" << endl;
    floatCalc.showResult();

    return 0;
}

In this example, we've defined a class template named Calculator, with two private member variables of type T. The class has methods for addition, subtraction, multiplication, and division, with results corresponding to the user-defined data types such as intand float. Objects of the class are created with specific data types, utilizing constructors to assign values.

Function templates behave similarly to regular functions but offer versatility in handling multiple data types within a single function. Like class templates, function templates promote code reuse and minimize programming efforts and maintenance.

Declaration of Function Templates:
template <class T>
T function_Name(T argument_list) {
    // Body of the function
}

In the above syntax:

  • templatedeclares the template function.
  • classis used to indicate a class template, but typename can also be employed interchangeably.
  • Tserves as a placeholder for the data type used by the function.

Let's consider an example to understand how to create and utilize a template function in C++:

FUNCTION TEMPLATES - C++ Copy to Clipboard  
#include <iostream>
using namespace std;

template <class T>
// Swap function: arguments passed by reference
void Swap(T &var1, T &var2) {
    T temp; // Temporary variable of type "T"
    temp = var1;
    var1 = var2;
    var2 = temp;
}

int main() {
    int int1 = 5, int2 = 10;
    float float1 = 5.1, float2 = 10.5;
    char char1 = 'a', char2 = 'b';

    cout << "Before using the function template.\n";
    cout << "int1 = " << int1 << "\nint2 = " 
         << int2;
    cout << "\nfloat1 = " << float1 << "\nfloat2 = " 
         << float2;
    cout << "\nchar1 = " << char1 << "\nchar2 = " 
         << char2;

    Swap(int1, int2);
    Swap(float1, float2);
    Swap(char1, char2);

    cout << "\n================================" << endl;
    cout << "After passing data to function template.\n";
    cout << "int1 = " << int1 << "\nint2 = " << int2;
    cout << "\nfloat1 = " << float1 << "\nfloat2 = " 
         << float2;
    cout << "\nchar1 = " << char1 << "\nchar2 = " 
         << char2;

    return 0;
}

In the above example, we call the Swapfunction by passing references to swap variables.