Question
VisualStudio C++ Make sure it runs and add comments to answer the questions Lab Manual - Templates Objective Implement template functions Implement template classes Implement
VisualStudio C++ Make sure it runs and add comments to answer the questions Lab Manual - Templates
Objective
- Implement template functions
- Implement template classes
- Implement templates with multiple types
Function Templates
Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one variable type or class without repeating the code for each type. This is achieved through template parameters. A template parameter is a special kind of parameter that can be used to pass a type as parameter. These function templates can use these parameters as if they were regular types. The format for declaring function templates with type parameters is:
template
While defining a function template the body of the function definition is preceded by a statement template
Exercise 1:
- Write two function templates GetMax and GetMin that take two arguments and return the maximum and minimum of the two respectively.
- Then paste the following code in your source file and run the program. The program should run peacefully.
int main ()
{
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);
n=GetMin(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
- Now remove the <int> and <long> from the code above and execute again. Does the program still work?
- Now replace the main function above with the main given below. You will need to change the code (declaration and definition) for GetMin and GetMax so that the following code works without an error.
int main ()
{
char i=Z;
int j=6, k;
long l=10, m=5, n;
k=GetMax(i,m);
n=GetMin(j,l);
cout << k << endl;
cout << n << endl;
return 0;
}
- Now remove the
and from this new main and re-run the program, is there any trouble with this version?
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started