Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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 function_declaration;

While defining a function template the body of the function definition is preceded by a statement template . The identifier can then be used as the data type of the parameters, the return type of the function, the data type of local variables and/or the data types of parameters.

Exercise 1:

  1. Write two function templates GetMax and GetMin that take two arguments and return the maximum and minimum of the two respectively.
  2. 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;
} 
 
  1. Now remove the <int> and <long> from the code above and execute again. Does the program still work?
  2. 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;
}
 
 
  1. 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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Database Management

Authors: Jeffrey A. Hoffer Fred R. McFadden

9th Edition

B01JXPZ7AK, 9780805360479

More Books

Students also viewed these Databases questions