Templates and Exception Handling in C++

 TEMPLATES 

• Template is a concept which enables us to define generic classes and functions and thus provides support for generic programming 

• Generic types are used as parameters in programs so that they work for a variety of suitable data types 

• For instance, in a class template, when an object of a specific type is defined for actual use, the template definition for that class is substituted with the required data type


FUNCTION TEMPLATE 

• C++ allows the use of function template, which is a generic type of function 

• The type is determined at compile time 

• Function template cannot qualify unless it has at least one argument of generic type

• In function overloading, there are as many function declarations and function definitions as the number of different function signatures we need 

• Advantages of function template over function overloading 

  1.  No code repetition 
  2.  Less chance of errors and bugs 
  3.  Object code gets reduced and hence the execution speed is enhanced


General Syntax: 

template T someFunction (T args) 

…… 

} 


• ‘template’ and ‘class’ are keywords 

• ‘T’ is a generic type

 • The return type can be a generic type or any basic data type


Q. Program to display largest among 2 numbers using function template.

#include <iostream>
using namespace std;
// template function
template <class T>
T Large(T n1, T n2)
{
    return (n1 > n2) ? n1 : n2;
}
int main()
{
    int i1, i2;
    float f1, f2;
    char c1, c2;
    cout << "Enter two integers: " << endl;
    cin >> i1 >> i2;
    cout << Large(i1, i2) << " is larger" << endl;
    cout << endl
         << "Enter two float numbers: " << endl;
    cin >> f1 >> f2;
    cout << endl
         << Large(f1, f2) << " is larger" << endl;
    cout << endl
         << "Enter two characters: " << endl;
    cin >> c1 >> c2;
    cout << Large(c1, c2) << " has larger ASCII value" << endl;
    return 0;
}




FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS

Syntax: 

template <class T1,class T2>
 ret_type func_name (args of types T1, T2,….) 
….
 }

#include <iostream>
using namespace std;
template <class T1, class T2>
void display(T1 x, T2 y)
{
    cout << x << “\t” << y << endl;
}

int main()
{
    cout << “Call with integer and character”;
    display(45, 'Z');
    cout << endl
         << “Call with float and
        integer”;
    display(22.22, 77);
    return 0;
}