Simple Class Template Program Example Get Maximum Number

Generic Programming

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types

Class Template Definition

A class template provides a specification for generating classes based on parameters. Class templates are generally used to implement containers. A class template is instantiated by passing a given set of types to it as template arguments.The C++ Standard Library contains many class templates, in particular, the containers adapted from the Standard Template Library, such as vector.

Class Template Syntax

template <class identifier>

class template_class_name {
    templete_identifier args;
  public:
 template_class_name(){
 }
 
 templete_identifier fn_name(templete_identifier .. args) {
  return ...
 }
};

Simple Class Template Program

// Header Files
#include<iostream>
#include<stdio.h>
#include<conio.h>

using namespace std;

// Template Declaration

template<class T>

// Template Class
class TClassMax {
    T x, y;
public:

    TClassMax() {

    }

    TClassMax(T first, T second) {
        x = first;
        y = second;
    }

    T getMaximun() {
        if (x > y)
            return x;
        else
            return y;
    }
};

int main() {
    TClassMax <int> iMax; // (100, 75);
    int a, b, i;
    TClassMax <float> fMax; // (90.78, 750.98);
    float c, d, j;

    cout << "Class Template Programs : Generic Programming : Get Maximum Number \n";
    cout << "Enter A,B values(integer):";
    cin >> a>>b;
    iMax = TClassMax<int>(a, b);
    i = iMax.getMaximun();
    cout << "Result Max Int : " << i;

    cout << "\n\nEnter C,D values(float):";
    cin >> c>>d;
    fMax = TClassMax<float>(c, d);
    j = fMax.getMaximun();
    cout << "Result Max Float : " << j;

    getch();
    return 0;
}

Sample Output

Class Template Programs : Generic Programming : Get Maximum Number
Enter A,B values(integer):90
89
Result Max Int : 90

Enter C,D values(float):100.32
123.89
Result Max Float : 123.89