• Register
100 points
5 1

C++ programming provides a facility to build templete for generic programming.It is very powerful tool in C++ because it will make your coding life easier and you will be one step ahead from normal programmers.In many cases you have to write same function again and again because of accepting different datatypes like:one function accepts int arguments and same function accepts one float and one int arguments.In order toget rid of writing functions again and again you can use templetes.

There are two types of templetes are:

  1. Function templete:It is a templete which generates generic functions.
  2. Class templete:It is a templete which generates generic classes.

Generic function or class can be created using keyword templete.This defines a set of operations that can be applied to the various types of data.A class keyword is used to specify a generic type in a template declaration.T is a placeholder name for a any data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type in main function.

Example of function templete

template <class T>
void swap1(T &a,T &b){//function templete
    T temp = a;
    a = b;
    b = temp;
}

Example of Class templete

template <class T1, class T2>//Generalising programming which accepts arguments any datatype
float funcAverage(T1 a, T2 b){//class templete
    float avg=(a+b)/2.0;
    
    return avg;
}

I am here writing one combined code which will clear all your doubts regarding templete.It will make you understand that why we are using templetes and gives you glimpse regarding class & function templetes.

#include<iostream>
using namespace std;
float funcAverage1(int a, int b){//specific programming style which accepts arguments here only int datatype
    float avg=(a+b)/2.0;
    return avg;
}
float funcAverage2(float a, int b){//Again and again using same function with different data as arguments
    float avg=(a+b)/2.0;
    return avg;
}
template <class T>
void swap1(T &a,T &b){//function templete
    T temp = a;
    a = b;
    b = temp;
}
template <class T1, class T2>//Generalising programming which accepts arguments any datatype
float funcAverage(T1 a, T2 b){//class templete
    float avg=(a+b)/2.0;
    
    return avg;
}
int main(){
    float final;
    final=funcAverage1(2,3);
    printf("Average of these numbers:%.3f\n",final);
    final=funcAverage2(2.5,3);
    printf("Average of these numbers:%.3f\n",final);
    
    int x=3,y=5;
    swap1(x,y);
    cout<<x<<endl<<y;
    return 0;
}