" friend void MyFunction<Foo<T>>; // doesn't do what you really want!\n",
" friend void MyFunction(Foo<T>); // doesn't do what you really want!\n",
"\n",
"};\n",
"````\n",
...
...
@@ -61,7 +61,7 @@
"{\n",
"\n",
" template<class U>\n",
" friend void MyFunction<Foo<U>>; // Ok!\n",
" friend void MyFunction(Foo<U>); // Ok!\n",
"\n",
"};\n",
"````\n",
...
...
%% Cell type:markdown id: tags:
# [Getting started in C++](/) - [Templates](/notebooks/4-Templates/0-main.ipynb) - [TP 11](/notebooks/4-Templates/1b-TP.ipynb)
%% Cell type:markdown id: tags:
<h1>Table of contents<spanclass="tocSkip"></span></h1>
<divclass="toc"><ulclass="toc-item"><li><span><ahref="#Introduction"data-toc-modified-id="Introduction-1">Introduction</a></span></li><li><span><ahref="#EXERCICE-37:-make-PowerOfTwoApprox-a-template-class"data-toc-modified-id="EXERCICE-37:-make-PowerOfTwoApprox-a-template-class-2">EXERCICE 37: make <code>PowerOfTwoApprox</code> a template class</a></span></li><li><span><ahref="#EXERCICE-38:-consistency"data-toc-modified-id="EXERCICE-38:-consistency-3">EXERCICE 38: consistency</a></span></li><li><span><ahref="#[optional]-EXERCICE-39:-crude-error-handling-for-the-overflow-issue"data-toc-modified-id="[optional]-EXERCICE-39:-crude-error-handling-for-the-overflow-issue-4">[optional] EXERCICE 39: crude error handling for the overflow issue</a></span></li><li><span><ahref="#EXERCICE-40:-more-template-functions"data-toc-modified-id="EXERCICE-40:-more-template-functions-5">EXERCICE 40: more template functions</a></span></li><li><span><ahref="#[optional]-EXERCICE-41:-another-error-handling..."data-toc-modified-id="[optional]-EXERCICE-41:-another-error-handling...-6">[optional] EXERCICE 41: another error handling...</a></span></li></ul></div>
%% Cell type:markdown id: tags:
### Introduction
[This notebook](/notebooks/TP/HowTo.ipynb) explains very briefly your options to run the TP.
%% Cell type:markdown id: tags:
### EXERCICE 37: make `PowerOfTwoApprox` a template class
The integer type used for the `numerator_ `attribute of the `PowerOfTwoApprox` class was chosen arbitrarily. Make it a class template parameter.
Only this attribute will be modified: the denominator and the number of bits remain `int`.
Make sure to modify:
* The type of the data attribute.
* The type returned by the `Numerator()` method.
In the `TestDisplay` classes, we will for the moment keep instantiating the version with `int`.
**IMPORTANT:** For the friendship declaration in `PowerOfTwoApprox` to `operator*`, you need to specify another template for the function: you can't use the same as the class one:
````
template<class T>
class Foo
{
friend void MyFunction<Foo<T>>; // doesn't do what you really want!
friend void MyFunction(Foo<T>); // doesn't do what you really want!
};
````
````
template<class T>
class Foo
{
template<class U>
friend void MyFunction<Foo<U>>; // Ok!
friend void MyFunction(Foo<U>); // Ok!
};
````
%% Cell type:markdown id: tags:
### EXERCICE 38: consistency
So far, we aren't very self-consistent: we loosen the constraint on the type used to store the numerator, but it is used up against `int` elsewhere.
To highlight this, change `PowerOfTwoApprox` instantiation by replacing `int` by `short`: you should see warnings pop up...
To do so properly, you will have to make some classes and functions template. As you will see, doing such a change is rather cumbersome: it is better whenever possible to identify as soon as possible whether a template parameter is required or not.
We will do so step by step, each exercice dealing with part of the changes (this is
In the first step, we will:
* Modify both `operator*` signatures so that the return type and the argument use the template parameter rather than `int`.
* Make `TestDisplaySum` a template class as well: as it uses up directly `operator*`, you have to do it now.
**DON'T PANIC:** You should see warnings to solve... and disturbing runtime effects: the computation gets stuck (we were not very aware so far of overflow issues and we end up here with infinite or at least very long loops...)
Don't get me wrong: the issue is not the templates themselves, but the fact our code is not robust enough and that we didn't see it previously as we worked on types and values (no more than 16 bits...) for which the potentiel problems were not appearant.
%% Cell type:markdown id: tags:
### [optional] EXERCICE 39: crude error handling for the overflow issue
This exercice is not template-related, but as often in software programming, we have obviously to deal swiftly with the unforeseen issue at hand so that we can keep working on what we intended to implement in the first place.
We will provide several fixes: we want to be able to track down when overflow occurs, and be able to print with `PrintNumericalError()` method that an overflow happens rather than a garbage value.
If in the loop the numerator or the denominator is less than the one computed at the previous iteration, an overflow occurred. Implement a test and when this happens, exit the loop, print a message about the issue and set arbitrarily numerator and exponent to 0
- In `times_power_of_2`:
Before multiplying by 2., check number is less than half the maximum possible value for the type (use `std::numeric_limits<>::max()`).
We'll see [later](/notebooks/5-UsefulConceptsAndSTL/1-ErrorHandling.ipynb) how to deal more cleanly with error handlings.
Overflow in times_power_of_2 with number = 1073741824 and exponent = 1
Overflow happened in PowerOfTwoApprox constructor for value 0.65 over 16 bits; everything is therefore set arbitrarily to zero at the moment.
Overflow happened in PowerOfTwoApprox constructor for value 0.35 over 16 bits; everything is therefore set arbitrarily to zero at the moment.
[With 16 bits]: Overflow!
````
%% Cell type:markdown id: tags:
### EXERCICE 40: more template functions
We will first heed the warnings: there is a type inconsistency due to the fact this function expects `int` and is fed `short`. Make some functions template ones to fix some of the warnings: `times_power_of_2`, `max_int` and `round_as_int`.
**WARNING:** You may have a hard time fixing the one concerning `operator*` due to a pesky
````
warning: implicit conversion loses
integer precision: 'int' to 'short' [-Wconversion]
This is due to a specificity I was not aware of before preparing this very TP: an arithmetic operator involving two `short` actually returns an `int`! For more of this, see this [StackOverflow question](https://stackoverflow.com/questions/24371868/why-must-a-short-be-converted-to-an-int-before-arithmetic-operations-in-c-and-c). I actually wasn't aware of this because I never use `short`: I was told long ago it was often a pessimization compared to a mere `int` and didn't dig deeper than that; the issue we met here seems to confirm it is quirky to use.
One can fix the warning with an additional `static_cast`:
Overflow in times_power_of_2 with number = 16384 and exponent = 2
Overflow happened in PowerOfTwoApprox constructor for value 0.65 over 16 bits; everything is therefore set arbitrarily to zero at the moment.
Overflow in times_power_of_2 with number = 16384 and exponent = 2
Overflow happened in PowerOfTwoApprox constructor for value 0.35 over 16 bits; everything is therefore set arbitrarily to zero at the moment.
[With 16 bits]: Overflow!
````
%% Cell type:markdown id: tags:
### [optional] EXERCICE 41: another error handling...
_Optional: you may want to take the solution directly!_
Previous exercice should also underline another limitation: we may detect the errors in building a `PowerOfTwoApprox`, but all bets are off when we perform arithmetics... Once again templates aren't the cause of our issue, it's just that the problem was hidden with the `int` used beforehand.
The issue we have now is that in plain arithmetic operations between `short`, we may overflow, especially considering our test example in which coefficients are already in the thousands.
This [StackOverflow post](https://stackoverflow.com/questions/199333/how-to-detect-unsigned-integer-multiply-overflow) provides an interesting non-standard feature introduced in clang and gcc to deal with this: special functions that tell if an operation will overflow (other replies give hints to do so manually).
The functions to use are:
````
__builtin_add_overflow(T a, T b, T* sum)
__builtin_mul_overflow(T a, T b, T* product)
````
where T is the type considered; these functions return 0 if no overflow occurs (and result is in this case given in third argument).
Use them in `TestDisplaySum<IntT>::Display()` and `operator*(const PowerOfTwoApprox<IntT>& approx, IntT coefficient)` to control the arithmetic operations there.
_This notebook is an adaptation of a lecture prepared and redacted by David Chamont (CNRS) under the terms of the licence [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/)_
_The present version has been redacted by Sébastien Gilles and Vincent Rouvreau (Inria)_