Function Template | Template in C++ | Function template example

Function Template | Template in C++

Function templates are unique functions that can work with generic types. This enables us to make a function template whose functionality can be adjusted to more than one kind or class without rehashing the whole code for each sort. 
In C++ this can be accomplished utilizing template parameters. A template parameter is an exceptional sort of parameter that can be utilized to pass a sort as an argument: simply like normal function parameters can be utilized to pass esteems to a function, template parameters permit to pass likewise types to a function. These function templates can utilize these parameters as though they were some other ordinary sort.


Function Template Declaration

A function template begins with the keyword template and followed by parameter inside <>, followed by function declaration as written below

template <class P>
P func1(P argument)
{
  .......  ....   .....
}

where P is a template argument that accepts various data types and class is a keyword.

In this example, we will learn how to find the square, square root and cube root of a given number using C++.

In the example, we are going to use a function template.

Function template in C++

#include<iostream>
#include<cmath>
using namespace std;
 template<class T>
T square(T x)
{
return x*x;
}
 template<class T>
T square_root(T x)
{
return sqrt(x);
}
 template<class T>
T cube_root(T x)
{
return cbrt(x);
}
 int main()
{
double x;
cout<<“Enter a number : “;
cin>>x;
cout<<“Square = “<<square(x)<<endl;
cout<<“Square Root = “<<square_root(x)<<endl;
cout<<“Cube Root = “<<cube_root(x)<<endl;
return 0;
}
OUTPUT:
Enter a number : 27
Square = 729
Square Root = 5.19615
Cube Root = 3




You must be also searching for these programming languages : 


tags: Template Function, Template Function in C++,Template Function C++, Template Function, Template in C++ .

Post a Comment

Previous Post Next Post