Home Uncategorized Write a program illustrate function template for power of a number.

Write a program illustrate function template for power of a number.

SHARE

AIM: Write a c++ program to illustrate function template for power of a number.

THEORY:

In C++, function templates are functions that serve as a pattern for creating other similar functions. The basic idea behind function templates is to create a function without having to specify the exact type(s) of some or all of the variables. Instead, we define the function using placeholder types, called template type parameters. Once we have created a function using these placeholder types, we have effectively created a “function stencil”.

When you call a template function, the compiler “stencils” out a copy of the template, replacing the

placeholder types with the actual variable types from the parameters in your function call!

Using this methodology, the compiler can create multiple “flavors” of a function from one template

SOURCE CODE:

#include<iostream>
#include<math.h>
using namespace std;
template<class T>
T power(T x,int y)
{
   return pow(x,y);
}
int main()
{
   int a,b,x;
   float c,d,y;
   cout<<“enter a, b values:\n”;
   cin>>a>>b;
   cout<<“enter c, d values:\n”;
   cin>>c>>d;
   x=pow(a,b);
   y=pow(c,d);
   cout<<“x=”<<x<<“\n y=”<<y;
   return 0;
}

OUTPUT:
Enter a, b values:
9     6
Enter c, d values:
3     3
x=531441
y=27

Back to Programs.