C++

C++ : Templates

Class Template

A template or a generic class is a class, which does not have data type specific member variables (attributes).
When the template is instantiated, the actual data types are replaced in the code of the class definition.

C++ program to demonstrate an example of a class template.
The class templates creates an Array class that is parameterized by type T and size.

#include<iostream>
#include<string>
#include<vector>

// Below class template creates an Array of 'size' and type T 
template <typename T, int size>
class Array {

    private :
    T array[size];

    public:
    void Disp_Array_Info() {
        std :: cout << "Array type : " << typeid(T).name() << std :: endl;
        std :: cout << "Array size : " << size << std :: endl;
        std :: cout << std :: endl;
    }   
};

class Employee {
     private:
     int id;
     
     public:
     void DisplayId() {
         std :: cout << "Employee Id :" << id << std :: endl;
     }
};

int main() {

    Array<char, 5> arr_1;
    arr_1.Disp_Array_Info();

    Array<int, 400> arr_2;
    arr_2.Disp_Array_Info();

    Array<std :: string, 10> arr_3;
    arr_3.Disp_Array_Info();

    Array<Employee, 100> arr_4;
    arr_4.Disp_Array_Info();

    return 0;
}

Output

Array type : c
Array size : 5

Array type : i
Array size : 400

Array type : NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Array size : 10

Array type : 8Employee
Array size : 100


Copyright (c) 2019-2023, Algotree.org.
All rights reserved.