Wednesday, March 28, 2018

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


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,c;
            float d,y;
            cout<<"\n enter a,b values:";
            cin>>a>>b;
            cout<<"\n enter the values of c&d:";
            cin>>c>>d;
            x=pow(a,b);
            y=pow(c,d);
            cout<<"\n x="<<x<<"\n y="<<y;
            return 0;
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home