Templates

A template is a  formula for creating a generic class or a function. C++ templates enable you to define a family of functions or classes that can operate on different types of information.
A function template by itself is not a type, or a function, or any other entity. No code is generated from a source file that contains only template definitions. In order for any code to appear, a template must be instantiated: the template arguments must be determined so that the compiler can generate an actual function (or class, from a class template).

Que- Find maximum of different data types using templates in a generic function;

#include "iostream"
#include "string"
#include"conio.h"

using namespace std;

template <typename T>
T maximum (T a, T b) 
{ 
    return a < b ? b:a; 
} 
int main ()
{
    int i = 50;
    int j = 40;
    cout << "Maximum in (i, j): " << maximum(i, j) << endl; 
    double f = 16.9; 
    double g = 76.1; 
    cout << "Maximum in(f, g): " << maximum(f, g) << endl; 
    string h = "Tanu"; 
    string k = "Welcome"; 
    cout << "Maximum in(h, k): " << maximum(h, k) << endl; 
    cout<<"\nPROGRAMMING @ C#ODE STUDIO";
    getch();
    return 0;
}

 

template_ezy

EXCEPTION H.

QUE- Initialize data member name, roll no, cgpa and generate percentage from cgpa as ” percentage = cgpa * 9.5 “. raise exception if name starts with ‘A’ or ‘a’ , if cgpa < 7, or if roll no. exceeded from 50;

Answer;

#include"conio.h"
#include"iostream.h"
#include"string.h"
using std :: string;
int main()
{
    char name[25];
    float cgpa;
    int rn;
    float per;
    cout<<"\nENTER NAME : ";
    cin>>name;
    cout<<"\nENTER CGPA : ";
    cin>>cgpa;
    cout<<"\nENTER ROLL NO.: ";
    cin>>rn;
    try
    {
        if(cgpa<7)
            throw cgpa;
        if(name[0]=='A' || name[0]=='a')
            throw name;
        if(rn>50)
            throw rn;
        else
        {
            per=cgpa*9.5;
            cout<<"\nNAME :"<<name<<"\nROLL NO. :"<<rn;
            cout<<"\nPERCENTAGE : "<<per;
        }
    }
    catch(float x)
    {
        cout<<"\nPERCENTAGE CANT GEN. \nCGPA IS LESS : "<<x;
    }
    catch(char* ch)
    {
        cout<<"\nPERCENTAGE CANT GEN. \nNAME STARTS WITH 'A': "<<ch;
    }
    catch(int y)
    {
        cout<<"\nPERCENTAGE CANT GEN. \nROLL NO. EXCEDED : "<<y;
    }
    cout<<"\n\nPROGRAMMING @ C#ODE STUDIO";
    getch();
    return 0;
}

When Exception Raised –

EXP_STMC

 

When correct input has been given –

EXP_STMC2

Exception Handeling With Inheritance;

Question- Make a class time with member data day char, derive a class management from time class with member data dd,mm,yyyy and date and with member func get and display;

whenever date is greater than 31 or month is greater than 12 it throws the object and show error;

Answer-

#include"conio.h"
#include"iostream"
using namespace std;
class time
{
    protected:
        char day[10];
    public:
        time()
        {
            cout<<"\nTIME CONSTRUCTOR"<<endl;
        }
};
class mgt:public time
{
    long int dd,mm,yy;
    long int date1;
    public:
        mgt()
        {
            cout<<"\nMANAGEMENT CONSTRUCTOR"<<endl;
        }
        void get()
        {
            cout<<"\nENTER DAY : ";
            cin>>day;
            cout<<"\nDATE : <format = ddmmyyyy> : ";
            cin>>date1;
            dd=date1/1000000;
            mm=date1/10000;
            mm=mm%100;
            yy=date1%10000;
            if(mm>12 || dd>31)
                throw mgt(); //here whenever mm>12 or dd>31 it will raise exception;
        }
        void disp()
        {
            cout<<"\nDAY : "<<day<<"\tDATE :"<<dd<<"\tMONTH :"<<mm<<"\tYEAR :"<<yy;
        }
};
main()
{
    try
    {
        mgt m;
        m.get();
        m.disp();
    }
    catch(mgt m) //here catch fn take the argument as object;
    {
        cout<<"\nTRY TO INSERT CORRECT FORMAT >> WRONG FORMAT DETECTED";
    }
    cout<<"\n\nPROGRAMMING @ C#ODE STUDIO";
    getch();
    return 0;
}

When correct data is inserted –

EXP_INHER

When wrong date format is insered –

EXP_INHER2

EXCEPTION HANDELING_USING TEMPLATE

Question – Make a class template with the name ‘student’ with private data ‘name’ and ‘reg no’, pass marks of 1 subject as float or int using template function and raise a exception if marks is less than zero;

#include<conio.h>
#include<iostream.h>
#include<math.h>
using namespace std;
template<class t>
class student
{
      private:
              char name[25];
              int rn;
      public:
              t getdata(t);
};
template<class t>
t student<t>:: getdata(t m)
             {
                  cout<<"\nName:";
                  cin>>name;
                  cout<<"Reg No.:";
                  cin>>rn;
                  if(m < 0)
                  {
                          throw m;
                  }
                  else
                  {
                      cout<<"\nNAME : "<<name<<"\tREG NO. : "<<rn<<"\tMARKS : "<<m;
                  }
             }
main()
{
      try
      {
                  student <int> s1;
                  student <float> s2;
                  float m1;
                  int choice;
                  cout<<"\nMARKS:";
                  cin>>m1;
                  cout<<"\n1:Point Value, 2:Round of (Make choice) : ";
                  cin>>choice;
                  if( choice==1 )
                  {
                      s2.getdata(m1);
                     }
                  else
                  { 
                      int m2;
                      m2=(int)m1;
                      s1.getdata(m2);            
                  }
      }
      catch(int x)
      {
                cout<<"\nOUTPUT CANT GENERATE !! MARKS IS LESS THAN 0 ";
      }
      catch(float x)
      {
                cout<<"\nOUTPUT CANT GENERATE !! MARKS IS LESS THAN 0 ";
      }
      cout<<"\n\n\tPROGRAMMING AT C#ODE STUDIO";                          
      getch();
}

Without raising any exception case-

_exp

With an exception case –

_exp2

EXCEPTION HANDELING;

/*
A throw expression signals the error or exceptional condition.
You can use an object of any type as the operand of a throw expression.
This object is typically used to convey information about the error.

this is made up of these blocks :
1:try block
2:catch block
3:throw block

example:
*/

#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
    int a,b;
    cout<<"\nENTER DIVIDEND : ";
    cin>>a;
    cout<<"\nENTER DIVISOR : ";
    cin>>b;
    try
    {
    if(b==0)
    {
        throw b;
    }
    else
    {
        cout<<"\nANSWER IS : "<<a/b;
    }
    }
    catch(int x)
    {
        cout<<"\nYOU ARE TRYING TO DIVIDE A NUMBER BY ZERO, DIVISOR IS : "<<x;
    }
    cout<<"\nPROGRAMMING @ C#ODE STUDIO";
    getch();
}

exph1



 exph2

EXCEPTION HANDELING 1;

A throw expression signals the error or exceptional condition.
You can use an object of any type as the operand of a throw expression.
This object is typically used to convey information about the error.

this is made up of these blocks :
1:try block
2:catch block
3:throw block

TRY- You use a try block to indicate which areas in your program that might throw exceptions you want to handle immediately. You use function try block to indicate that you want to detect exceptions in the entire body of a function.

 

try
{
    divide(10, 0);
}
catch(int i)
{
    if(i==DivideByZero)
    {
        cerr<<"Divide by zero error";
    }
}

CATCH – You can declare a handler to catch many types of exceptions. The allowable objects that a function can catch are declared in the parentheses following the catch keyword
(the exception_declaration). you can catch objects of the fundamental types, base and derived class objects,
references, and pointers to all of these types.

catch (networkIOException& e)
 {

   Log error message in the exception object.
   OBJ << e.what();
}

THROW – You use a throw expression to indicate that your program has encountered an exception.

    try
    {
    if(b==0)
    {
        throw b;
    }
    else
    {
        cout<<"\nANSWER IS : "<<a/b;
    }
    }

CLASS TEMPLATES;

/*

using a class template we can modify the data in class by mean of any data type;

instruction will be executed whether it is int,char or float;

*/

#include<conio.h>
#include<iostream>
using namespace std;
template<class t>
class test
{
public:
     test();//constructor
     ~test();//destructor
     t data (t);
};
template<class t>
test<t>::~test()
{
     cout<<"\nDESTRUCTOR AWAKE";
}
template<class t>
test<t>::test()
{
     cout<<"\nCONSTRUCTOR AWAKE";
}
template<class t>
t test<t>::data(t var) //t will be worked as return type and argumented value also
{
      return var;
}
int main()
{
test <int> var1; //<int> denotes the data type for class object
test <float> var2;
test <char> var3;
test <char*> var4;
int i;
float j;
char k;
char l[10];
cout<<"\n\nENTER INT NUMBER : ";
cin>>i;
cout<<"\nENTER FLOAT NUMBER : ";
cin>>j;
cout<<"\nENTER ONE CHARACTER DATA : ";
cin>>k;
cout<<"\nENTER STRING : ";
cin>>l;
cout<<"\nINT NUMBER : "<<var1.data(i);
cout<<"\nFLOAT NUMBER : "<<var2.data(j);
cout<<"\nCHARACTER : "<<var3.data(k);
cout<<"\nSTRING : "<<var4.data(l);
cout<<"\n\n\tPROGRAMMING AT C#ODE STUDIO";
getch();
}

temp_class

FUNCTION TEMPLATES;

/*templates are used to manipulate any data type in one function.

Templates are a way of making your classes more abstract

by letting you define the behavior of the class without

actually knowing what datatype will be handled by the operations

of the class. In essence, this is what is known as generic programming;

syntax : template <class data_type>

<data_type> function_name (data_type <variable>); */

#include<conio.h>
#include<iostream>
using namespace std;
template<class t>
t func(t a) //t is working as return type and t is also an argument;
{
         return a;
}
int main()
{
        int data1;
        cout<<"\nINPUT <INT> DATA : ";
        cin>>data1;
        cout<<"DATA OF INT TYPE = "<<func(data1);
        float data2;
        cout<<"\n\nINPUT <FLOAT> DATA : ";
        cin>>data2;
        cout<<"DATA OF FLOAT TYPE = "<<func(data2);
        char data3[10];
        cout<<"\n\nINPUT <STRING> DATA : ";
        cin>>data3;
        cout<<"DATA OF STRING TYPE = "<<func(data3);
        cout<<"\n\n\tPROGRAMMING AT C#ODE STUDIO";
         getch();
}

 

templATE