Exercise 11:

Create a directory ex11 and store in this directory all the files corresponding to this exercise.

Question 1: Function templates.

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.

This question will help you checking 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.

This question will help you exercising your understanding of containers.

Your goal for this exercise is to implement a (template) container array. Please create a file named "Array.h" and type and complete the following code:

#ifndef ARRAY_H
#define ARRAY_H

template <class T>
class Array {
private:
 int _size; // size of the memory to allocate
 T* _data; // it will contain the data

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

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

// write the code below:
template <class T>
Array<T>::Array(int size) 
{
 // complete
}

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

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

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

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

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

#endif // ARRAY_H

The following is some code that you can type in a file named "test_array.cpp" to test your class Array:
#include <iostream>
#include "Array.h"

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

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

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