Lab 9: Templates in C++
Instructions
-
First read this page then start working on lab with the GitHub classroom link below.
-
Use the code in the GitHub repository for this lab.
-
Github Classroom Link: https://classroom.github.com/a/nLo-kCme
Objective
Develop an understanding of C++ templates, focusing on their application for code reusability and flexibility.
Exercise 1: Swap Function Template
Create a generic swap function using C++ templates that can interchange the values of two variables of any data type.
Put your code for this exercise in the swap.cpp file in the Exercise1 folder in your GitHub repository.
- Create a function template called
swapValuesthat can interchange the values of two variables of any data type. - The function should be able to handle different data types (e.g., int, float, double) for the the values to be swapped.
- Update the
mainfunction inswap.cppto demonstrate the usage of theswapValuesfunction for different data types. - In the
README.mdfile in your GitHub repository. Write a few sentences describing how you used a C++ template to create a genericswapValuesfunction.
Exercise 2: Area Function Templates
Create function templates to calculate the area of different geometric shapes.
Put your code for this exercise in the area.cpp file in the Exercise2 folder in your GitHub repository.
- Create three function templates that can calculate the area of different geometric shapes :
calculateAreaSquare,calculateAreaRectangle, andcalculateAreaCircle. - The function should be able to handle different data types (e.g., int, float, double) for the dimensions of the shapes.
- Update the
mainfunction inarea.cppto demonstrate the usage of the calculateArea functions for different shapes and data types. - In the
README.mdfile in your GitHub repository. Write a few sentences describing how you used a C++ template to create generic calculateArea functions.
Exercise 3: Vector Class Template
Implement a generic vector class in C++ using templates, providing a simplified version of the functionality offered by std::vector.
Put your code for this exercise in the Exercise3 folder in your GitHub repository.
- Write a template class GenericVector with a template parameter for the element type.
- Put this implementation into the files
GenericVector.handGenericVector.cpp - Use the non-generic versions
IntVector.handIntVector.cppfiles to help guide your coding. - Update the
mainfunction inmain.cppto demonstrate the usage ofGenericVectorfor different data types. Don’t forget to addGenericVector.htomain.cpp. - Modify the
Makefileso thatGenericVector.handGenericVector.cppare included when building themaintarget. - In the
README.mdfile in your GitHub repository. Write a few sentences describing how you used a C++ template to create generic vector class declaration and implementation.