Commit 0cc2b24d authored by GILLES Sebastien's avatar GILLES Sebastien
Browse files

Remove executed cells from git: we should strive to commit notebooks which...

Remove executed cells from git: we should strive to commit notebooks which kernels have just been cleared.
parent 10c68115
......@@ -193,7 +193,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -209,100 +209,9 @@
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[1minput_line_8:4:5: \u001b[0m\u001b[0;1;31merror: \u001b[0m\u001b[1mstatic_assert failed \"T must be an integer or a floating point!\"\u001b[0m\n",
" static_assert(std::is_arithmetic<T>(), \"T must be an integer or a floating point!\");\n",
"\u001b[0;1;32m ^ ~~~~~~~~~~~~~~~~~~~~~~~\n",
"\u001b[0m\u001b[1minput_line_10:3:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0min instantiation of function template specialization 'Convert2<std::__1::basic_string<char> >' requested here\u001b[0m\n",
" Convert2<std::string>(5); // Doesn't make sense so compiler will yell! \n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1minput_line_8:5:12: \u001b[0m\u001b[0;1;31merror: \u001b[0m\u001b[1mno matching conversion for static_cast from 'int' to 'std::__1::basic_string<char>'\u001b[0m\n",
" return static_cast<T>(value);\n",
"\u001b[0;1;32m ^~~~~~~~~~~~~~~~~~~~~\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:793:40: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: no known conversion from 'int' to 'const std::__1::basic_string<char,\n",
" std::__1::char_traits<char>, std::__1::allocator<char> >::allocator_type' (aka 'const std::__1::allocator<char>') for\n",
" 1st argument\u001b[0m\n",
" _LIBCPP_INLINE_VISIBILITY explicit basic_string(const allocator_type& __a)\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:800:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: no known conversion from 'int' to 'const std::__1::basic_string<char>' for 1st argument\u001b[0m\n",
" basic_string(const basic_string& __str);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:805:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: no known conversion from 'int' to 'std::__1::basic_string<char>' for 1st argument\u001b[0m\n",
" basic_string(basic_string&& __str)\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:820:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: no known conversion from 'int' to 'const char *' for 1st argument\u001b[0m\n",
" basic_string(const _CharT* __s) {\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:874:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: no known conversion from 'int' to 'initializer_list<char>' for 1st argument\u001b[0m\n",
" basic_string(initializer_list<_CharT> __il);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:860:18: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate template ignored: requirement '__can_be_converted_to_string_view<char, char_traits<char>, int>::value' was not\n",
" satisfied [with _Tp = int]\u001b[0m\n",
" explicit basic_string(const _Tp& __t);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:832:9: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor template not viable: requires 2 arguments, but 1 was provided\u001b[0m\n",
" basic_string(const _CharT* __s, const _Allocator& __a);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:845:9: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor template not viable: requires 3 arguments, but 1 was provided\u001b[0m\n",
" basic_string(size_type __n, _CharT __c, const _Allocator& __a);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:855:9: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor template not viable: requires at least 3 arguments, but 1 was provided\u001b[0m\n",
" basic_string(const _Tp& __t, size_type __pos, size_type __n,\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:864:18: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor template not viable: requires 2 arguments, but 1 was provided\u001b[0m\n",
" explicit basic_string(const _Tp& __t, const allocator_type& __a);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:868:9: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor template not viable: requires 2 arguments, but 1 was provided\u001b[0m\n",
" basic_string(_InputIterator __first, _InputIterator __last);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:871:9: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor template not viable: requires 3 arguments, but 1 was provided\u001b[0m\n",
" basic_string(_InputIterator __first, _InputIterator __last, const allocator_type& __a);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:790:31: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires 0 arguments, but 1 was provided\u001b[0m\n",
" _LIBCPP_INLINE_VISIBILITY basic_string()\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:801:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires 2 arguments, but 1 was provided\u001b[0m\n",
" basic_string(const basic_string& __str, const allocator_type& __a);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:813:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires 2 arguments, but 1 was provided\u001b[0m\n",
" basic_string(basic_string&& __str, const allocator_type& __a);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:835:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires 2 arguments, but 1 was provided\u001b[0m\n",
" basic_string(const _CharT* __s, size_type __n);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:839:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires 2 arguments, but 1 was provided\u001b[0m\n",
" basic_string(size_type __n, _CharT __c);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:876:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires 2 arguments, but 1 was provided\u001b[0m\n",
" basic_string(initializer_list<_CharT> __il, const _Allocator& __a);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:837:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires 3 arguments, but 1 was provided\u001b[0m\n",
" basic_string(const _CharT* __s, size_type __n, const _Allocator& __a);\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:850:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires at least 2 arguments, but 1 was provided\u001b[0m\n",
" basic_string(const basic_string& __str, size_type __pos,\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m\u001b[1m/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:847:5: \u001b[0m\u001b[0;1;30mnote: \u001b[0mcandidate constructor not viable: requires at least 3 arguments, but 1 was provided\u001b[0m\n",
" basic_string(const basic_string& __str, size_type __pos, size_type __n,\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m"
]
},
{
"ename": "Interpreter Error",
"evalue": "",
"output_type": "error",
"traceback": [
"Interpreter Error: "
]
}
],
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#include <string>\n",
"\n",
......@@ -333,7 +242,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -352,7 +261,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -364,7 +273,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -377,18 +286,9 @@
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Integer hold: 5\n",
"String hold: Hello world!\n"
]
}
],
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#include <iostream>\n",
"#include <string>\n",
......@@ -416,7 +316,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -438,7 +338,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -450,7 +350,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -470,7 +370,7 @@
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -484,7 +384,7 @@
},
{
"cell_type": "code",
"execution_count": 11,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -510,7 +410,7 @@
},
{
"cell_type": "code",
"execution_count": 12,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -529,7 +429,7 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -543,7 +443,7 @@
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -562,31 +462,9 @@
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[1minput_line_24:3:13: \u001b[0m\u001b[0;1;31merror: \u001b[0m\u001b[1mtemplate argument for template type parameter must be a type\u001b[0m\n",
" MyArray<5ul, 5ul> array1(2); // COMPILATION ERROR!\n",
"\u001b[0;1;32m ^~~\n",
"\u001b[0m\u001b[1minput_line_21:1:16: \u001b[0m\u001b[0;1;30mnote: \u001b[0mtemplate parameter is declared here\u001b[0m\n",
"template<class TypeT, std::size_t Nelts>\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m"
]
},
{
"ename": "Interpreter Error",
"evalue": "",
"output_type": "error",
"traceback": [
"Interpreter Error: "
]
}
],
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"{\n",
" MyArray<5ul, 5ul> array1(2); // COMPILATION ERROR!\n",
......@@ -595,31 +473,9 @@
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[1minput_line_25:3:18: \u001b[0m\u001b[0;1;31merror: \u001b[0m\u001b[1mtemplate argument for non-type template parameter must be an expression\u001b[0m\n",
" MyArray<int, int> array1(2); // COMPILATION ERROR!\n",
"\u001b[0;1;32m ^~~\n",
"\u001b[0m\u001b[1minput_line_21:1:35: \u001b[0m\u001b[0;1;30mnote: \u001b[0mtemplate parameter is declared here\u001b[0m\n",
"template<class TypeT, std::size_t Nelts>\n",
"\u001b[0;1;32m ^\n",
"\u001b[0m"
]
},
{
"ename": "Interpreter Error",
"evalue": "",
"output_type": "error",
"traceback": [
"Interpreter Error: "
]
}
],
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"{\n",
" MyArray<int, int> array1(2); // COMPILATION ERROR!\n",
......
%% Cell type:markdown id: tags:
# [Getting started in C++](/) - [Templates](/notebooks/4-Templates/0-main.ipynb) - [Introduction](/notebooks/4-Templates/1-Intro.ipynb)
%% Cell type:markdown id: tags:
<h1>Table of contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Motivation" data-toc-modified-id="Motivation-1">Motivation</a></span></li><li><span><a href="#Function-templates-(or-methods)" data-toc-modified-id="Function-templates-(or-methods)-2">Function templates (or methods)</a></span><ul class="toc-item"><li><span><a href="#static_assert" data-toc-modified-id="static_assert-2.1"><code>static_assert</code></a></span></li></ul></li><li><span><a href="#Class-templates" data-toc-modified-id="Class-templates-3">Class templates</a></span><ul class="toc-item"><li><span><a href="#Template-method-of-a-template-class" data-toc-modified-id="Template-method-of-a-template-class-3.1">Template method of a template class</a></span></li></ul></li><li><span><a href="#Type-or-non-type-template-parameter" data-toc-modified-id="Type-or-non-type-template-parameter-4">Type or non-type template parameter</a></span></li><li><span><a href="#Few-precisions-about-templates" data-toc-modified-id="Few-precisions-about-templates-5">Few precisions about templates</a></span></li></ul></div>
%% Cell type:markdown id: tags:
## Motivation
The typical introduction to the need of generic programming is implementing a function that determines the minimum between two quantities (by the way don't do that: STL provides it already...)
%% Cell type:code id: tags:
``` C++17
int min(int lhs, int rhs)
{
return lhs < rhs ? lhs : rhs;
}
```
%% Cell type:code id: tags:
``` C++17
double min(double lhs, double rhs)
{
return lhs < rhs ? lhs : rhs;
}
```
%% Cell type:code id: tags:
``` C++17
float min(float lhs, float rhs)
{
return lhs < rhs ? lhs : rhs;
}
```
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
std::cout << min(5, -8) << std::endl;
std::cout << min(5., -8.) << std::endl;
std::cout << min(5.f, -8.f) << std::endl;
}
```
%% Cell type:markdown id: tags:
Already tired? Yet we have still to define the same for unsigned versions, other types such as `short` ou `long`... And it's not very [**DRY** (Don't Repeat Yourself)](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself): you may have noticed the implementation is exactly the same!
## Function templates (or methods)
A mechanism was therefore introduced in C++ to provide only one implementation: the **templates**:
%% Cell type:code id: tags:
``` C++17
template<class T>
T min2(T lhs, T rhs)
{
return lhs < rhs ? lhs : rhs;
}
```
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
std::cout << min2<int>(5, -8) << std::endl;
std::cout << min2(5, -8) << std::endl;
std::cout << min2(5., -8.) << std::endl;
std::cout << min2(5.f, -8.f) << std::endl;
}
```
%% Cell type:markdown id: tags:
As you can see:
* The type is replaced by a parameter (here called `T`)
* In the function call, you might specify the type explicitly between brackets (`<>`). If not specified, the compiler may figure it out if said type is used for one of the parameters. In other words, for the following case it won't work:
%% Cell type:code id: tags:
``` C++17
template<class T>
T Convert(int value)
{
return static_cast<T>(value);
}
```
%% Cell type:code id: tags:
``` C++17
{
Convert(5); // Error: can't figure out which type `T` to use!
}
```
%% Cell type:code id: tags:
``` C++17
{
Convert<double>(5); // Ok
}
```
%% Cell type:markdown id: tags:
You may have see noticed there are no constraints on `T` whatsoever. If you invoke a template and the implementation doesn't make sense for the chosen type the compiler will yell (no doubt you have already seen compilers are extremely talented to do so and it is even truer regarding templates...)
%% Cell type:code id: tags:
``` C++17
#include <string>
{
Convert<std::string>(5); // Doesn't make sense so compiler will yell!
}
```
%% Cell type:markdown id: tags:
### `static_assert`
Of course, it would be nicer to get a clearer error message when an impossible type is provided... C++ 20 should introduce the [concept](https://en.cppreference.com/w/cpp/language/constraints) to constraint properly which type is acceptable, but C++ 11 already introduced a way slightly better than C++ 03 with `static_assert`:
%% Cell type:code id: tags:
``` C++17
#include <type_traits> // for std::is_arithmetic
template<class T>
T Convert2(int value)
{
static_assert(std::is_arithmetic<T>(), "T must be an integer or a floating point!");
return static_cast<T>(value);
}
```
%% Cell type:code id: tags:
``` C++17
#include <string>
{
Convert2<std::string>(5); // Doesn't make sense so compiler will yell!
// But first line is much clearer than previously...
}
```
%%%% Output: stream
input_line_8:4:5: error: static_assert failed "T must be an integer or a floating point!"
static_assert(std::is_arithmetic<T>(), "T must be an integer or a floating point!");
 ^ ~~~~~~~~~~~~~~~~~~~~~~~
input_line_10:3:5: note: in instantiation of function template specialization 'Convert2<std::__1::basic_string<char> >' requested here
Convert2<std::string>(5); // Doesn't make sense so compiler will yell!
 ^
input_line_8:5:12: error: no matching conversion for static_cast from 'int' to 'std::__1::basic_string<char>'
return static_cast<T>(value);
 ^~~~~~~~~~~~~~~~~~~~~
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:793:40: note: candidate constructor not viable: no known conversion from 'int' to 'const std::__1::basic_string<char,
std::__1::char_traits<char>, std::__1::allocator<char> >::allocator_type' (aka 'const std::__1::allocator<char>') for
1st argument
_LIBCPP_INLINE_VISIBILITY explicit basic_string(const allocator_type& __a)
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:800:5: note: candidate constructor not viable: no known conversion from 'int' to 'const std::__1::basic_string<char>' for 1st argument
basic_string(const basic_string& __str);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:805:5: note: candidate constructor not viable: no known conversion from 'int' to 'std::__1::basic_string<char>' for 1st argument
basic_string(basic_string&& __str)
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:820:5: note: candidate constructor not viable: no known conversion from 'int' to 'const char *' for 1st argument
basic_string(const _CharT* __s) {
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:874:5: note: candidate constructor not viable: no known conversion from 'int' to 'initializer_list<char>' for 1st argument
basic_string(initializer_list<_CharT> __il);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:860:18: note: candidate template ignored: requirement '__can_be_converted_to_string_view<char, char_traits<char>, int>::value' was not
satisfied [with _Tp = int]
explicit basic_string(const _Tp& __t);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:832:9: note: candidate constructor template not viable: requires 2 arguments, but 1 was provided
basic_string(const _CharT* __s, const _Allocator& __a);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:845:9: note: candidate constructor template not viable: requires 3 arguments, but 1 was provided
basic_string(size_type __n, _CharT __c, const _Allocator& __a);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:855:9: note: candidate constructor template not viable: requires at least 3 arguments, but 1 was provided
basic_string(const _Tp& __t, size_type __pos, size_type __n,
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:864:18: note: candidate constructor template not viable: requires 2 arguments, but 1 was provided
explicit basic_string(const _Tp& __t, const allocator_type& __a);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:868:9: note: candidate constructor template not viable: requires 2 arguments, but 1 was provided
basic_string(_InputIterator __first, _InputIterator __last);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:871:9: note: candidate constructor template not viable: requires 3 arguments, but 1 was provided
basic_string(_InputIterator __first, _InputIterator __last, const allocator_type& __a);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:790:31: note: candidate constructor not viable: requires 0 arguments, but 1 was provided
_LIBCPP_INLINE_VISIBILITY basic_string()
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:801:5: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
basic_string(const basic_string& __str, const allocator_type& __a);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:813:5: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
basic_string(basic_string&& __str, const allocator_type& __a);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:835:5: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
basic_string(const _CharT* __s, size_type __n);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:839:5: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
basic_string(size_type __n, _CharT __c);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:876:5: note: candidate constructor not viable: requires 2 arguments, but 1 was provided
basic_string(initializer_list<_CharT> __il, const _Allocator& __a);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:837:5: note: candidate constructor not viable: requires 3 arguments, but 1 was provided
basic_string(const _CharT* __s, size_type __n, const _Allocator& __a);
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:850:5: note: candidate constructor not viable: requires at least 2 arguments, but 1 was provided
basic_string(const basic_string& __str, size_type __pos,
 ^
/Users/Shared/Software/miniconda3/envs/cling/include/c++/v1/string:847:5: note: candidate constructor not viable: requires at least 3 arguments, but 1 was provided
basic_string(const basic_string& __str, size_type __pos, size_type __n,
 ^

%%%% Output: error
Interpreter Error:
%% Cell type:markdown id: tags:
`static_assert` evolved in C++ 14:
* In C++ 11, it takes two arguments: the test and a string which features an explanation on the topic at hand.
* In C++ 14 and above, you might just give the test; it is actually handy when the test is already crystal clear:
````static_assert(std::is_same<T, int>(), "Check T is an integer");```` is a tad overkill!
That being said, if the test is not that trivial you should really use the possibility to add an explanation.
## Class templates
We have seen templates in the case of functions, but classes can be templated as well:
%% Cell type:code id: tags:
``` C++17
template<class T>
class HoldAValue
{
public:
HoldAValue(T value);
T GetValue() const;
private:
T value_;
};
```
%% Cell type:code id: tags:
``` C++17
template<class T>
HoldAValue<T>::HoldAValue(T value) // the <T> is mandatory to identify properly the class
: value_(value)
{ }
```
%% Cell type:code id: tags:
``` C++17
template<class T>
T HoldAValue<T>::GetValue() const
{
return value_;
}
```
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <string>
{
HoldAValue integer(5);
std::cout << "Integer hold: " << integer.GetValue() << std::endl;
HoldAValue<std::string> string("Hello world!"); // If type not specified explicitly it would have been char*...
std::cout << "String hold: " << string.GetValue() << std::endl;
}
```
%%%% Output: stream
Integer hold: 5
String hold: Hello world!
%% Cell type:markdown id: tags:
The template must be reminded in the definition as well; please notice before the `::` the brackets with the parameters *without their type*.
### Template method of a template class
Notice a template class may provide template methods:
%% Cell type:code id: tags:
``` C++17
template<class T>
class HoldAValue2
{
public:
HoldAValue2(T value);
T GetValue() const;
template<class U>
U Convert() const;
private:
T value_;
};
```
%% Cell type:code id: tags:
``` C++17
template<class T>
HoldAValue2<T>::HoldAValue2(T value)
: value_(value)
{ }
```
%% Cell type:code id: tags:
``` C++17
template<class T>
T HoldAValue2<T>::GetValue() const
{
return value_;
}
```
%% Cell type:markdown id: tags:
In this case there are two `template` keyword for the definition: one for the class and the other for the method:
%% Cell type:code id: tags:
``` C++17
template<class T> // template type for the class first
template<class U> // then template type for the method
U HoldAValue2<T>::Convert() const
{
return static_cast<U>(value_);
}
```
%% Cell type:code id: tags:
``` C++17
{
HoldAValue2 hold(9);
hold.Convert<double>();
}
```
%% Cell type:markdown id: tags:
## Type or non-type template parameter
The examples so far are using **type** parameters: the `T` in the example stands for a type and is deemed to be substituted by a type. Templates may also use **non type** parameters, which are in most cases `enum` or `integral constant` types (beware: floating point types parameters or `std::string` **can't** be used as template parameters!)
Both can be mixed in a given template declaration:
%% Cell type:code id: tags:
``` C++17
template<class TypeT, std::size_t Nelts>
class MyArray
{
public:
explicit MyArray(TypeT initial_value);
private:
TypeT content_[Nelts];
};
```
%% Cell type:code id: tags:
``` C++17
template<class TypeT, std::size_t Nelts>
MyArray<TypeT, Nelts>::MyArray(TypeT initial_value)
{
for (auto i = 0ul; i < Nelts; ++i)
content_[i] = initial_value;
}
```
%% Cell type:code id: tags:
``` C++17
{
MyArray<int, 5ul> array1(2);
MyArray<double, 2ul> array2(3.3);
}
```
%% Cell type:markdown id: tags:
However, you can't provide a type parameter where a non-type is expected (and vice-versa):
%% Cell type:code id: tags:
``` C++17
{
MyArray<5ul, 5ul> array1(2); // COMPILATION ERROR!
}
```
%%%% Output: stream
input_line_24:3:13: error: template argument for template type parameter must be a type
MyArray<5ul, 5ul> array1(2); // COMPILATION ERROR!
 ^~~
input_line_21:1:16: note: template parameter is declared here
template<class TypeT, std::size_t Nelts>
 ^

%%%% Output: error
Interpreter Error:
%% Cell type:code id: tags:
``` C++17
{
MyArray<int, int> array1(2); // COMPILATION ERROR!
}
```
%%%% Output: stream
input_line_25:3:18: error: template argument for non-type template parameter must be an expression
MyArray<int, int> array1(2); // COMPILATION ERROR!
 ^~~
input_line_21:1:35: note: template parameter is declared here
template<class TypeT, std::size_t Nelts>
 ^

%%%% Output: error
Interpreter Error:
%% Cell type:markdown id: tags:
## Few precisions about templates
* Template parameters must be known or computed at **compile time**. You can't therefore instantiate a template from a value that was entered by the user of the program or computed at runtime.
* In the template syntax, `class` might be replaced by `typename`:
%% Cell type:code id: tags:
``` C++17
template<typename T>
T Convert3(int value)
{
return static_cast<T>(value);
}
```
%% Cell type:markdown id: tags:
There are exactly zero differences between both keywords; some authors suggest conventions (e.g. use `typename` for POD types and `class` for the more complicated types) but they are just that: conventions!
* The definition of the templates must be provided in header files, not in compiled files. The reason is that the compiler can't know all the types for which the template might be used: you may use `std::min` for your own defined types (provided they define a `<` operator...) and obviously STL writers can't foresee which type you will come up with!
* The compiler will generate the code for each type given to the template; for instance if `Convert<double>`, `Convert<unsigned int>` and `Convert<short>` are used in your code, the content of this template function will be instantiated thrice! This can lead to **code bloat**: lots of assembler code is generated, and compilation time may increase significatively.
* So templates are a _very_ nice tool, but make sure to use them only when they're relevant, and you may employ techniques to limit the amount of code actually defined within the template definitions.
%% Cell type:markdown id: tags:
© _CNRS 2016_ - _Inria 2018-2019_
_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)_
......
......@@ -75,13 +75,13 @@
"source": [
"### EXERCICE 38: consistency\n",
"\n",
"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. \n",
"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` anywhere else. \n",
"\n",
"To highlight this, change `PowerOfTwoApprox` instantiation by replacing `int` by `short`: you should see warnings pop up...\n",
"\n",
"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.\n",
"\n",
"We will do so step by step, each exercice dealing with part of the changes (this is \n",
"We will do so step by step, each exercice dealing with part of the changes.\n",
"\n",
"In the first step, we will:\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<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Introduction" data-toc-modified-id="Introduction-1">Introduction</a></span></li><li><span><a href="#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><a href="#EXERCICE-38:-consistency" data-toc-modified-id="EXERCICE-38:-consistency-3">EXERCICE 38: consistency</a></span></li><li><span><a href="#[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><a href="#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><a href="#[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!
};
````
````
template<class T>
class Foo
{
template<class U>
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.
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` anywhere else.
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
We will do so step by step, each exercice dealing with part of the changes.
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.
To do so, a boolean argument should be added to:
- `PowerOfTwoApprox` constructor _[input/output]_
- `TestDisplay::PrintNumericalError()` method _[input]_
- `times_power_of_2()` function _[input/output]_
- `max_int()` function _[input/output]_
that is set to true if an overflow occurred.
The two overflows to track down are:
- In `PowerOfTwoApprox` constructor:
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.
The output should look something like:
````
[With 4 bits]: 0.65 ~ 0.625 (10/2^4) [error = 38462/1000000]
[With 8 bits]: 0.65 ~ 0.648438 (166/2^8) [error = 2404/1000000]
[With 12 bits]: 0.65 ~ 0.649902 (2662/2^12) [error = 150/1000000]
[With 16 bits]: 0.65 ~ 0.649994 (42598/2^16) [error = 9/1000000]
[With 4 bits]: 0.35 ~ 0.34375 (11/2^5) [error = 17857/1000000]
[With 8 bits]: 0.35 ~ 0.349609 (179/2^9) [error = 1116/1000000]
[With 12 bits]: 0.35 ~ 0.349976 (2867/2^13) [error = 70/1000000]
[With 16 bits]: 0.35 ~ 0.349998 (45875/2^17) [error = 4/1000000]
[With 4 bits]: 0.65 * 3515 + 0.35 * 4832 = 3976 ~ 3857 [error = 29930/1000000]
[With 8 bits]: 0.65 * 3515 + 0.35 * 4832 = 3976 ~ 3968 [error = 2012/1000000]
[With 12 bits]: 0.65 * 3515 + 0.35 * 4832 = 3976 ~ 3975 [error = 252/1000000]
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]
return times_power_of_2(approx.Numerator() * coefficient, -approx.Exponent());
````
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`:
%% Cell type:code id: tags:
``` C++17
// Doesn't run in Xeus-cling
template<class IntT>
IntT operator*(const PowerOfTwoApprox<IntT>& approx, IntT coefficient)
{
// static_cast to deal with the `short` case
return static_cast<IntT>(times_power_of_2(approx.Numerator() * coefficient, -approx.Exponent()));
}
```
%% Cell type:markdown id: tags:
If you're doing such a cast though, you should end up with something like:
````
[With 4 bits]: 0.65 ~ 0.625 (10/2^4) [error = 38462/1000000]
[With 8 bits]: 0.65 ~ 0.648438 (166/2^8) [error = 2404/1000000]
[With 12 bits]: 0.65 ~ 0.649902 (2662/2^12) [error = 150/1000000]
[With 16 bits]: 0.65 ~ 0.649994 (42598/2^16) [error = 9/1000000]
[With 4 bits]: 0.35 ~ 0.34375 (11/2^5) [error = 17857/1000000]
[With 8 bits]: 0.35 ~ 0.349609 (179/2^9) [error = 1116/1000000]
[With 12 bits]: 0.35 ~ 0.349976 (2867/2^13) [error = 70/1000000]
[With 16 bits]: 0.35 ~ 0.349998 (45875/2^17) [error = 4/1000000]
[With 4 bits]: 0.65 * 3515 + 0.35 * 4832 = 3976 ~ -2286 [error = 1574950/1000000]
[With 8 bits]: 0.65 * 3515 + 0.35 * 4832 = 3976 ~ 1 [error = 999748/1000000]
[With 12 bits]: 0.65 * 3515 + 0.35 * 4832 = 3976 ~ 0 [error = 1000000/1000000]
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.
Expected result is something like:
````
[With 4 bits]: 0.65 ~ 0.625 (10/2^4) [error = 38462/1000000]
[With 8 bits]: 0.65 ~ 0.648438 (166/2^8) [error = 2404/1000000]
[With 12 bits]: 0.65 ~ 0.649902 (2662/2^12) [error = 150/1000000]
[With 16 bits]: 0.65 ~ 0.649994 (42598/2^16) [error = 9/1000000]
[With 4 bits]: 0.35 ~ 0.34375 (11/2^5) [error = 17857/1000000]
[With 8 bits]: 0.35 ~ 0.349609 (179/2^9) [error = 1116/1000000]
[With 12 bits]: 0.35 ~ 0.349976 (2867/2^13) [error = 70/1000000]
[With 16 bits]: 0.35 ~ 0.349998 (45875/2^17) [error = 4/1000000]
Overflow in 3515 * 10
Overflow in operator*(PowerOfTwoApprox, integer)! Arbitrary value MAX_INT will therefore be returned.
Overflow in 4832 * 11
Overflow in operator*(PowerOfTwoApprox, integer)! Arbitrary value MAX_INT will therefore be returned.
Overflow in 3515 * 10/2^4 + 4832 * 11/2^5
[With 4 bits]: Overflow!
Overflow in 3515 * 166
Overflow in operator*(PowerOfTwoApprox, integer)! Arbitrary value MAX_INT will therefore be returned.
Overflow in 4832 * 179
Overflow in operator*(PowerOfTwoApprox, integer)! Arbitrary value MAX_INT will therefore be returned.
Overflow in 3515 * 166/2^8 + 4832 * 179/2^9
[With 8 bits]: Overflow!
Overflow in 3515 * 2662
Overflow in operator*(PowerOfTwoApprox, integer)! Arbitrary value MAX_INT will therefore be returned.
Overflow in 4832 * 2867
Overflow in operator*(PowerOfTwoApprox, integer)! Arbitrary value MAX_INT will therefore be returned.
Overflow in 3515 * 2662/2^12 + 4832 * 2867/2^13
[With 12 bits]: Overflow!
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:
© _CNRS 2016_ - _Inria 2018-2019_
_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)_
......
......@@ -55,7 +55,7 @@
"#include <string>\n",
"\n",
"template<> // notice the empty brackets!\n",
"std::string Convert(int value)\n",
"std::string Convert<std::string>(int value)\n",
"{\n",
" std::cout << \"std::string instantiation called!\" << std::endl; \n",
" return std::to_string(value);\n",
......@@ -488,7 +488,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -509,7 +509,7 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
......@@ -530,7 +530,7 @@
},
{
"cell_type": "code",