× back Templates Class templates
Next Topic → ← Previous Topic

Generic programming using template

Benefits of generic programming

Templates

Why template?

  • If we want to use a single function which can handle different data types then either we can use function overloading or template.
  • Template over function overloading??
    • In function overloading have to repeat our code while making function with same name but with different data type.
    • While using template we have to write the function definition once.

For example, normally we were doing this ↓

                    
int Max(int n, int m)
{
    return (n < m) ? n : m; // ternary operator
}

float Max(float n, float m)
{
    return (n < m) ? n : m;
}
                    
                

Observation:

  • Same algorithm: body of function is same in each case.
    They are completely differnt functions because they handle different types of arguments & return value.
  • This is time consuming & waste of space.
  • Using template you need to write such function just once, and it works for many different data type.

Now we will use template ↓

                    
template <class T>
T Max(T n, T m)
{
    return (n > m) ? n : m;
}
                    
                

Key feature:

  • Represent the data type used by the function i.e T, it is also called template argument.

What the compiler does?

At compile time:

  • Compiler do nothing for template function.
  • It cannot generate code as it don't know data type.
  • It remember template function for future reference.
  • Code generation of template function take place when that function is invoked.
                                    
    int x = 3, y = 9;
    r = Max(x, y);
                                    
                                
    Now compiler know that type is 'int'.
  • So it generates a specific version of the Max() function for type int.

Programs

                            
#include <iostream>
using namespace std;

template <class Type>
Type Max(Type a, Type b)
{
    return (a > b) ? a : b;
}

int main()
{
    float r;
    r = Max(9, 4);
    cout << "Maximum number is : " << r << endl;
    r = Max(54.89, 98.78);
    cout << "Maximum number is : " << r << endl;

    return 0;
}
     
                            
                        

output ↓

                    
Maximum number is : 9
Maximum number is : 98.78
                    
                   
                      
#include <iostream>
using namespace std;

template <class Type>
void Print(Type a)
{
    cout << "The value is : " << a << endl;
}

int main()
{
    Print(9);
    Print(9.5);
    Print("Curry Power");
    return 0;
}

                      
                  

Output ↓

                
The value is : 9
The value is : 9.5
The value is : Curry Power
                
               
                       
                       
#include <iostream>
using namespace std;
template <class Type>
Type add(Type num1, Type num2)
{
    return num1 + num2;
}
int main()
{
    int a = 10, b = 20;
    float x = 10.2, y = 20.2;
    cout << "Sum of " << a << " and " << b << " is = " << add(a, b) << endl;
    cout << "Sum of " << x << " and " << y << " is = " << add(x, y) << endl;
    return 0;
}
                       
                   
                       
#include <iostream>
using namespace std;
template <class Type>
void swap(Type *num1, Type *num2)
{
    Type temp = *num1;
    *num1 = *num2;
    *num2 = temp;
}
int main()
{
    int a = 10, b = 20;
    cout << " a and b before swap : " << a << " " << b << endl;
    swap(&a, &b);
    cout << " a and b after swap : " << a << " " << b << endl;
    return 0;
}
                       
                   
                       
#include <iostream>
using namespace std;
template <class Type>
Type max(Type arr[], int size)
{
    Type max = arr[0];
    for (int i = 1; i < size; i++)
    {
        if (arr[i] > max)
            max = arr[i];
    }
    return max;
}
int main()
{
    int arr[] = {1, 2, 33, 4, 5};
    int size = sizeof(arr) / sizeof(int);
    cout << " max number in integer array is : " << max(arr, size) << endl;
    float arr2[] = {1.1, 2.2, 33.3, 4.4, 5.5};
    size = sizeof(arr2) / sizeof(int);
    cout << " max number in float array is : " << max(arr2, size) << endl;
    return 0;
}
                       
                   

Class Templates in OOP using C++

Class Templates syntax ↓

                
Template <class Type>
Class class_name
{
    // class body
};
                
            

Class Templates object Syntax ↓

                
Class_name <template argument> object_name;
                
            
                
Test<int> objINT;
Test<float> objFLOAT;
                
            

Program ↓

                   
#include <iostream>
using namespace std;
template <class Type>
class Test
{
private:
    Type n;

public:
    void getValue()
    {
        cin >> n;
    }
    void printVal()
    {
        cout << "you entered : " << n << endl;
    }
};
int main()
{
    Test<int> objINT;
    cout << "Enter integer value : ";
    objINT.getValue();
    objINT.printVal();
    
    Test<float> objFLOAT;
    cout << "Enter real value : ";
    objFLOAT.getValue();
    objFLOAT.printVal();

    return 0;
}
                   
               

Reference ↓