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);
}
- Write the template version of this function but call it
maximum
- Instanciate the function with two parameters of the same type
- Instanciate the function with two parameters of different types
- Instanciate the function with two parameters with differents types but casting the parameter to avoid the error message
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:
- Choose a regular (not template) class whose use is properly tested (unit testing can be useful to achieve that)
- Create a new file, update the guards
- Copy the declaration and the implementation of the non parameterized version
- Add the template parameter to the class and the deported methods
- Reuse the testing code, update it with instanciating the template
- Run the tests
- Go to 1 until everything is OK :-)
You can instanciate your generic class with types different from double
and int
.
- A template is a model that is never compiled (only instanciations are)
- If a template is not instanciated, the compiler may not look over it.
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.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10