×
BLUE
function Templates in c++



function Templates in c++
  14 August 2021
Read more Like this Post.
templates is the super method of c++ in which we operate a function without any data-type like int, char, float, etc. this function  work on any data-type, or return type.
watch the video if you don't understand with text tutorials.

lets make a simple function which swap the values of two integers.
void swap_values(int &k, int &x){
    int temp = x;
    x = k;
    k = temp;
}

this function swap the values of tow variables. but this function only work on integers we want to swap others data-types like float, double, char, string, etc. if we made swap function for every data-type it's too long. therefore we use templates and replace all the data-types with template type like.
template
void swap_values(T &k, T &x){
    T temp = x;
    x = k;
    k = temp;
}
we use a keyword template and declare a data-type T then replace all the data-types with T. like integers we replace with it. T is the name of the new Data-type this can have any name. this function work as integer when we pass integers in parameters, this work as float when we pass floating point in parameters like so on.
let's show all code of the program.

#include 
#include
using namespace std;

template
void swap_values(T &k, T &x){
T temp = x;
x = k;
k = temp;
}


int main(){
int a = 30;
int b = 40;
cout << "before a: " << a << "\t b: " << b << endl;
swap_values(a, b);
cout << "after a: " << a << "\t b: " << b << endl;

string fname = "zohaib";
string lname = "khan";
cout << "before fname: " << fname << "\t lname: " << lname << endl;
swap_values(fname, lname);
cout << "after fname: " << fname << "\t lname: " << lname;
return 1;
}

output of the code:
before a: 30     b: 40
after  a: 40     b: 30
before fname: zohaib     lname: khan
after  fname: khan     lname: zohaib


this the simple swapping function with templates now create more function like this for addition, multiplication, division.

Related Post's

Not Loaded Zohaib Jozvi
0 14 August 2021
Read Latest Post.
Read other post.