Respuesta :
Answer:
#include<iostream>
#include<math.h>
using namespace std;
//create the template function
template<class TypeVar>
TypeVar absValue(TypeVar a1){
return fabs(a1);
}
//main function
int main(){
//display
cout<<"Absolute value of -3 is "<<absValue(-3)<<endl;
cout<<"Absolute value of 5 is "<<absValue(5)<<endl;
cout<<"Absolute value of -4.5 is "<<absValue(-4.5)<<endl;
cout<<"Absolute value of 3.2 is "<<absValue(3.2)<<endl;
return 0;
}
Explanation:
Create the template which can work with any type like int, float, double.
syntax of the template:
template<class identifier>
then, the identifier is used in place of type and it works in all types.
The template is used in the code for making our function works for a different type of data, not limited to a single type.
After that, create the function with type TypeVar which is an identifier for our template and declare the one parameter with the same type.
and then, it returns the absolute value. the function used to convert into an absolute value is fabs().
it takes one parameter and it can be int, float and double.
Then, create the main function for testing our function.
call the function with a pass by value in the argument and it prints the output on the screen.