Exercise 11:

Create a directory ex11 and store in this directory the files corresponding to your solutions for the following questions.

Question 1: Function templates (25 points).

This question will help you to check your understanding of function templates.

In a file "utils.h" write the code for the following template functions:

Write a simple test file "test_function_template.cpp" that demonstrates your functions for: int and double.

Question 2: Class templates (25 points).

This question will help to check your understanding of class templates.

For this question, you will re-use the code from the exercise 10, question 1 (operations on matrices). Copy the file "Matrix.h" from ex. 10 q. 1 in the present directory and modify it to be a class template.

You can type the following code in a file "test_matrix_template.cpp" to test your template Matrix class:
#include <iostream>
#include "Matrix.h"

int main() {
 Matrix<double> m1(1.0, 0.0, 1.0, 0.0);
 Matrix<double> m2;
 m2(0,0) = 1.0;
 m2(0,1) = 1.0;
 m2(1,0) = 1.0;
 m2(1,1) = 1.0;

 Matrix<double> m3;
 m3 = m1 + m2;
 std::cout << m3 << std::endl;

 m3 = m1 - m2;
 std::cout << m3 << std::endl;

 m3 = m1 * m2;
 std::cout << m3 << std::endl;
}
It should give similar results to the results obtained in the previous exercise.

Question 3: Container (50 points).

This question is for exercising your understanding of containers.

Your goal for this exercise is to implement a parameterized container Vec. Please create a file named "Vec.h" and type and complete the following code:

#ifndef VEC_H
#define VEC_H

template <class T>
class Vec {
private:
 int _size; // size of the memory to allocate
 T* _data;  // Vec is representated as an array

public:
 Vec(int size = 100);
 Vec(const Vec<T>& a);
 ~Vec();

 int get_size() const { return _size; }
 Vec<T>& operator= (const Vec<T>& a);
 T& operator[] (int i);
 const T& operator[] (int i) const;
};

template <class T>
Vec<T>::Vec(int size) 
{
 // complete
}

template <class T>
Vec<T>::~Vec() 
{
 // complete
}

template <class T>
Vec<T>::Vec(const Vec<T>& a)
{
 // complete
}

template <class T>
Vec<T>& Vec<T>::operator= (const Vec<T>& a) 
{
 // complete
}

template <class T>
T& Vec<T>::operator[] (int i) 
{
 // complete
}

template <class T>
const T& Vec<T>::operator[] (int i) const
{
 // complete
}

#endif // Vec_H

The following code is used to test Vec. Create a file named "test_array.cpp" and type in the following code:
#include <iostream>
#include "Vec.h"

int main () {
  Vec<double> a(10);
  for (int i = 0; i < a.get_size(); i++)
    a[i] = i;

  Vec<double> a2=a;
  for (int i = 0; i < a2.get_size(); i++)
    std::cout << a2[i] << std::endl;

  Vec<double> a3;
  a3 = a;
  for (int i = 0; i < a3.get_size(); i++)
    std::cout << a3[i] << std::endl;
}