C++ TEMPLATE

For saving us from writing the same code again and again for different data types, comes the concept of the template.

As we know sometimes, we need to perform the same operation for different data types. For example, performing a sort operation for int and char or any other data type.

Instead of writing the same code again and again for different data types, we write one code using the concept of the template and pass the data type as the parameter.

For better understanding look at the diagram below.

As you can see, we need only one code, while we pass data types as parameters and while running whole code adjusts according to data type. Also, we can not only use templates only for functions but also for classes. The following example is an illustration of it.

Code:



  #include "iostream"
  using namespace std;

  template  class Array {

  private:
    T* ptr;
    int size;

  public:
    Array(T arr[], int s);void print();
  };

  template  Array::Array(T arr[], int s)
  {
    ptr = new T[s];
    size = s;
    for (int i = 0; i < size; i++)
    ptr[i] = arr[i];
  }

  template  void Array::print()
  {
    for (int i = 0; i < size; i++)
    cout << " " << *(ptr + i);
    cout << endl;
  }

  int main()
  {
    int arr[5] = { 1, 2, 3, 4, 5 };
    Array a(arr, 5);
    a.print();
    return 0;
  }
          

Output:


1 2 3 4 5






© Copyright 2022 Advanced PLC. All rights reserved.