tete du loic

 Loïc YON [KIUX]

  • Enseignant-chercheur
  • Référent Formation Continue
  • Responsable des contrats pros ingénieur
  • Référent entrepreneuriat
  • Responsable de la filière F2 ingénieur
  • Secouriste Sauveteur du Travail
mail
loic.yon@isima.fr
phone
(+33 / 0) 4 73 40 50 42
location_on
ISIMA
  • twitter
  • linkedin
  • viadeo

[C++] TP 7

Lire en Français

First publication date: 2020/06/05

In this practical work, we will see the genericity and its applications for functions and classes.

Template functions

You need to use the max() function seen in class:

const int& max(const int& a,const int & b) {
    return ((a > b) ? a : b);
}

Template classes

Almost automatic writing

You have to adapt the dynamic vector of reals and the stack of integers from the previous practical works.

Here a reminder of the recipe seen in class:

  1. Choose a regular (not template) class whose use is properly tested (unit testing can be useful to achieve that)
  2. Create a new file, update the guards
  3. Copy the declaration and the implementation of the non parameterized version
  4. Add the template parameter to the class and the deported methods
  5. Reuse the testing code, update it with instanciating the template
  6. Run the tests
  7. Go to 1 until everything is OK :-)

You can instanciate your generic class with types different from double and int.

With experience, you will write directly the template version.

If you used unit testing for the regular class, the tests can be used easily with the generic class using a typedef.

typedef GenStack<int> Stack;

TEST_CASE("default constructor") {
   Stack s; 
   
   CHECK(  s.empty() );
   CHECK(  0 == s.size() );
}

Template friend function

The template friend functions are easy to write depending where they are implemented (inside or outside the class)...

inline (inside) version

template <typename T>
class GenVector {
   
   friend GenVector operator+(const GenVector &a, const GenVector& b) {
       return ...;
   }
};

Outside

template <typename T>
class GenVector {
   
  template <typename U> friend GenVector<U> operator+(const GenVector<U> &, const GenVector<U>&) ;
   
};

template <typename T>
GenVector<T> operator+(const GenVector<T> & a, const GenVector<T> & b) {
  
}

You want more ?

If you want to implement another data structure, you can find a generic linked list... In this exercise, you will encounter the notions of iterators and operator++() overloading.

Red string ...

You will have to implement a clone() method or a copy() method that allows to get a copy of the current object. The method is constant and virtual, defined in the Shape class. It must return a Shape * pointer.

With a covariant return type property, the overriding methods in the specialized classes can return a pointer on a daughter class instead of the super class pointer.

You will have more work to do with the clone() method from the Group class.