Exercise 10:

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

Question 1: Operator overloading.

This question will test your understanding of operator overloading. In this exercise, your goal is to complete the given code for a class Matrix (this class represents 2 x 2 matrices over R) by defining the operations '+', '-', '*', which are the traditional addition, subtraction and multiplication of matrices. Please type and complete the following code in a file named "Matrix.h":
#include <stdexcept>
#include <iostream>

#ifndef MATRIX_H
#define MATRIX_H

class Matrix {
public:
 Matrix() {
  _a[0] = 0.0; _a[1] = 0.0; 
  _a[2] = 0.0; _a[3] = 0.0;
 }
 Matrix(double a00, double a01, 
        double a10, double a11) 
 {
  _a[0] = a00; _a[1] = a01;
  _a[2] = a10; _a[3] = a11;
 }
 Matrix(const Matrix& m) {
  _a[0] = m._a[0]; _a[1] = m._a[1];
  _a[2] = m._a[2]; _a[3] = m._a[3];
 }
 
 Matrix& operator= (const Matrix& m) {
  _a[0] = m._a[0]; _a[1] = m._a[1];
  _a[2] = m._a[2]; _a[3] = m._a[3];
 }
 // to return the elt (i,j) of a matrix
 double operator() (int i, int j) const {
  if (i < 0 || i > 1 || j < 0 || j > 1)
    throw std::runtime_error("WrongIndex");
  return _a[2*i + j];
 }

 // to access the elt (i,j) of a matrix and modify it
 double& operator() (int i, int j) {
  if (i < 0 || i > 1 || j < 0 || j > 1)
    throw std::runtime_error("WrongIndex");
  return _a[2*i + j];
 }

private:
 double _a[4]; // _a[0] = a00  _a[1] = a01
               // _a[2] = a10  _a[3] = a11
};

// Write the code below corresponding to:
// 1) the addition of two matrices
// 2) the subtraction of one matrix from the other
// 3) the multiplication of two matrices

// In addition: overload the operator "<<" in order to nicely print a matrix

#endif // MATRIX_H 
To test your code, you can type the following code in a file "test_matrix.cpp":
#include <iostream>
#include "Matrix.h"

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

 Matrix 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;
}

Question 2: Introduction to generic programming.

This question will test your understanding of generic programming.

Create two files: "utils.h" and "test_generic_programming.cpp".

In "utils.h" write a template function min() that returns the minimum of two elements. You can get inspiration from the function max() defined in the lecture slides.

In "test_generic_programming.cpp" write a main() function to test your min() function. You can reuse a similar example to the one presented in the lecture slides.