-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.qmd
770 lines (581 loc) · 17.8 KB
/
index.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
---
title: "The New ISO Standard C++20"
author: "Bernd Doser"
date: July 2022
date-format: "MMMM YYYY"
institute: "[HITS gGmbH](https://h-its.org)"
format:
revealjs:
logo: images/HITS_RGB_eng.jpg
footer: "C++20 (B. Doser)"
slide-number: true
highlight-style: a11y
---
## This presentation is available at{.center}
[https://bernddoser.github.io/workshop-cpp20](https://bernddoser.github.io/workshop-cpp20)
## Agenda
::: {.incremental}
- Warm-up with C++
- Important C++11 features
- C++20 features
- Concepts, ranges
- Modules, coroutines
- std::format, three-way comparison
- Coding competition
:::
<!-- TODO
- Modules
- Concepts
- Meta programming
- Reflections
Exercises:
- C++98 Warm-up matrix
- Smart pointer
- Move semantic
- Concepts
- Ranges
- Three-way comparison
- format
- Pancakes
-->
## My Background
::: {.incremental}
- PhD in theoretical chemistry
- Linear scaling electron-electron correlation
- C++ scientific software developer since 2004
- Automatic differentiation for tailor-made force fields ([AMS GmbH Freiburg](https://avmatsim.eu/))
- Open source projects @ HITS:
[GROMACS-FDA](https://github.com/HITS-MBM/gromacs-fda), [GROMACS-RAMD](https://github.com/HITS-MCM/gromacs-ramd), [PINK](https://github.com/HITS-AIN/PINK), [HiFlow3](https://emcl-gitlab.iwr.uni-heidelberg.de/hiflow3.org/hiflow3), [TACO](https://github.com/HITS-TOS/TACO)
- Personal open source projects:
[BlasBooster](https://github.com/BrainTwister/BlasBooster), [GeneHunter](https://github.com/BrainTwister/GeneHunter)
:::
## Why C++?
::: {.incremental}
- High performance
- Multi-paradigm
- Imperative
- Object-oriented
- Generic
- Functional
- Strong type system
- Strict backward compatibility
:::
## ISO Standardization
- C++98: First ISO Standard
- C++11: Smart pointers, move sematic, Lambda functions, range-based for loop, auto
- C++14: Variable templates, generic lambdas
- C++17: Structured bindings
- C++20: Modules, concepts, coroutines, ranges
- Suggestions for C++23: "A plan for ranges", reflections
## ISO Timeline
[![](images/iso-timeline.png)](https://isocpp.org/std/status)
## Books and ISO Standard
::: columns
::: {.column width="60%"}
![](images/book_stroustrup.jpg){.border width="180" height="250"}
![](images/book_josuttis.jpg){.border width="180" height="250"}
![](images/book_gottschling.jpg){.border width="180" height="250"}
![](images/book_vandevoorde.jpg){.border width="180" height="250"}
![](images/book_cukic.jpg){.border width="180" height="250"}
![](images/book_grimm.jpg){.border width="180" height="250"}
:::
::: {.column width="40%"}
- C++20 ISO Standard: ISO/IEC 14882:2020
- Commercial version ~200 EUR
- [Free working draft](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4849.pdf)
:::
:::
::: notes
- Show ranges concept
:::
## Helpful Links and Tools
::: {layout-ncol=2}
- [cppreference.com](https://cppreference.com)
- [CompilerExplorer](https://gcc.godbolt.org)
- [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines)
- [Overview C++20 by Oleksandr Koval](https://oleksandrkvl.github.io/2021/04/02/cpp-20-overview.html)
![](images/compiler_explorer.png)
:::
::: notes
- Compiler feature support with proposals
- Explain CompilerExplorer
- Show C++ Guidlines (best practice)
:::
## C++98 Warm-up
```cpp
class Matrix
{
public:
Matrix(int m, int n)
: m(m), n(n), mat(m*n)
{}
Matrix operator * (Matrix B) {
Matrix C(this->m, B.n);
/* C(i,j) = sum_k A(i,k) * B(k,j) */
return C;
}
private:
int m,n;
std::vector<double> mat;
};
```
[![](images/godbolt-icon.svg){height=40}
Task: Find the performance issue.](https://godbolt.org/z/cbbEbYcr9)
## Carbage Collection vs. RAII
::: {.callout-note icon=false}
## Carbage Collection (Java, Python, Go)
- Automatic memory management, which periodically stops all threads and frees unreferenced memory.
- Extra overhead
:::
::: {.callout-note icon=false}
## RAII: Resource Aquisition is Initialization (C++, Rust)
- The lifetime of a resource will be bound to the lifetime of a local variable. C++ automatically manages the lifetime of locals.
- Smart pointers (C++11) overcome the manually memory deallocation.
C++ principle: "Don't pay for something you don't use."
:::
## Raw pointers (before C++11)
- Manual allocation and deallocation of memory
- Segmentation faults
- Memory leaks
```cpp
void func()
{
int* valuePtr = new int(42);
if ( /* ... */ ) return; // memory leak
delete valuePtr;
}
```
::: {.callout-note}
Raw pointers (`new`) are deprecated in C++20 and will be removed in C++23.
:::
## Smart pointers (C++11)
```cpp
#include <memory>
void func()
{
std::shared_ptr<int> ptr (new int(42));
if ( /* ... */ )
return; // no memory leak
}
```
Better:
```cpp
std::shared_ptr<int> ptr = std::make_shared<int>();
```
Best:
```cpp
auto ptr = std::make_shared<int>();
```
## Smart pointers (C++11)
::: {.callout-note icon=false}
## `std::unique_ptr<T>`
- Allows exactly one owner of the underlying pointer
- Can be moved to a new owner, but not copied or shared
:::
::: {.callout-note icon=false}
## `std::shared_ptr<T>`
- Reference-counted smart pointer
- The raw pointer is not deleted until all owners have gone out of scope
:::
::: {.callout-note icon=false}
## `std::weak_ptr<T>`
- Required to break circular references between `shared_ptr`
:::
## Smart pointers (C++11)
```{.cpp code-line-numbers="1-4|6-10|1,12-17"}
auto p1 = std::make_shared<int>(1);
auto p2 = p1;
assert(*p2 == 1);
assert(p1.use_count() == 2);
auto p3 = std::make_unique<int>(2);
// auto p4 = p3; // unique_ptr can't be copied
auto p5 = std::move(p3);
assert(*p5 == 2);
assert(p3 == nullptr);
// auto p6 = std::weak_ptr<int>(3); // weak_ptr can't own
auto p6 = std::weak_ptr<int>(p1);
assert(p6.use_count() == 2);
p1.reset();
p2.reset();
assert(p6.expired());
```
[![](images/godbolt-icon.svg){height=40}
Exercise](https://godbolt.org/z/dErqbrYM4)
## Move Semantics (C++11)
:::{.callout-tip icon=false}
## L-values will be copied
- Permanent objects with a name and a storage address
- Copy is expensive
:::
:::{.callout-tip icon=false}
## R-values will be moved
- Temporary objects without a name and a storage address
- R-values can only appear on the right side in an assignment
- Move is fast
:::
[![](images/godbolt-icon.svg){height=40}
Exersice](https://godbolt.org/z/x737PaMjK)
## Containers
| Name | Description |
|------------------|---------------------------------------|
| `array` | static contiguous array |
| `vector` | dynamic contiguous array |
| `list` | linked list |
| `set` | sorted collection of unique keys |
| `map` | sorted collection of key-value pairs |
| `unordered_set` | hashed collection of unique keys |
| `unordered_map` | hashed collection of key-value pairs |
## C++20: New Keywords
::: columns
::: {.column width="50%"}
- Concepts
- `concept`
- `requires`
- Coroutines
- `co_await`
- `co_return`
- `co_yield`
:::
::: {.column width="50%"}
- Modules
- `import`
- `module`
- Others
- `constinit`
- `consteval`
- `char8_t`
:::
:::
## Modules
- Modules are a new way to organize C++ code into logical components
- Problems of the obsolete header files
- Repetitive compilation of the same code
- Inclusion order-dependent headers
- Cyclic dependencies
- Macros leakage in and out from headers
- Poor encapsulation of implementation details
## Modules
```cpp
// math.cppm
export module math;
export int add(int fir, int sec)
{
return fir + sec;
}
// client.cpp
import math;
int main()
{
add(2000, 20);
}
```
- Modules are orthogonal to namespaces.
## Coroutines: Evolution of Functions
```cpp
int f1() { return 1; } // A C-like function
int f2(int arg) { return arg; } // Function overloading
double f2(double arg) { return arg; }
template <typename T> // Function template
T f3(T arg) { return arg; }
struct F4 { // Functor
int operator()() { return 4; }
};
auto f5 = [] (int i) { return i * i; }; // Lambda (C++11)
auto f6 = [] (auto arg) { // Generic lambda (C++14)
return std::to_string(arg);
};
```
## Coroutines
- A coroutine is a generalisation of a function that allows the function to be suspended and then later resumed.
- A coroutine is stackless: their state is stored in heap, not on stack
- A coroutine contains one of these keywords:
- `co_return` (coroutine return statement)
- `co_await` (await expression)
- `co_yield` (yield expression)
## Coroutines: CppCoro
- Coroutines provides a very low-level interface.
- [CppCoro](https://github.com/lewissbaker/cppcoro) provides asynchronous programming abstractions (maybe in C++23)
- `Task<T>`: asynchronous computation that is executed lazily
- `Generator<T>`: a coroutine type that produces a sequence of values of type `T` where values are produced lazily and synchronously.
## Coroutines: Generator
```cpp
Generator<int> getNext(int start = 0, int step = 1) {
auto value = start;
while (true) {
co_yield value;
value += step;
}
}
auto gen = getNext(100, -10);
for (int i = 0; i <= 20; ++i) {
gen.next();
std::cout << gen.getValue() << " ";
}
```
## Concepts
- With concepts, failure happens early and the error message is much more meaningful.
- Before C++20 `enable_if` was used to check template arguments ([Example](https://github.com/BrainTwister/BlasBooster/blob/c1bd253971ea831f6e1b844568c2d69dfec4e239/include/BlasBooster/Core/DenseMatrix.h#L72)).
```cpp
// C++11
template <typename T> // Substitution failure is not an error (SFINAE)
std::enable_if_t<std::is_same_v<T, int>> f(T x);
// C++20
void f(std::same_as<int> auto x);
```
## Concepts: Example
- Definition
```cpp
template <typename T>
concept Incrementable = requires(T x) { x++; ++x; };
```
- Usage
```cpp
template <Incrementable T>
void inc(T t);
template <Incrementable T>
void inc(T t) requires Incrementable<T>;
void inc(Incrementable auto t);
```
## The World Before Ranges (C++11)
```cpp
#include <algorithm>
int main()
{
std::vector<int> data{42, 1, 12, -3, 14, -5};
std::vector<int> pos;
// copy only positive numbers:
std::copy_if(data.begin(), data.end(),
std::back_inserter(pos), [](int i){ return i >= 0; });
}
```
[cppreference std::copy_if](https://en.cppreference.com/w/cpp/algorithm/copy)
```cpp
template <class InputIt, class OutputIt, class UnaryPredicate>
OutputIt copy_if( InputIt first, InputIt last,
OutputIt d_first,
UnaryPredicate pred );
```
[![](images/godbolt-icon.svg){height=40}
Exercise](https://gcc.godbolt.org/z/7EMhaWd5q)
## Ranges: What We Want
- Direct usage of containers without iterators (pointers)
```cpp
std::vector<int> v{1,2,3};
std::sort(std::begin(v), std::end(v));
std::ranges::sort(v);
```
- Chaining similar to unix pipes
```cpp
result = data | func1 | func2 | ...
```
- Lazy evaluation
## Ranges: filter
```cpp
#include <ranges>
#include <vector>
int main()
{
std::vector<int> data{42, 1, 12, -3, 14, -5};
auto even = [](int i){return i >= 0;};
auto pos = data | std::views::filter(even);
}
```
[![](images/godbolt-icon.svg){height=40}
Exercise](https://gcc.godbolt.org/z/T5W6K46Gb)
## Ranges: How it works
- A `range` is a concept, not a container
- Defined in header `<ranges>`:
```cpp
template < class T >
concept range = requires( T& t ) {
ranges::begin(t);
ranges::end(t);
};
```
::: {.smaller}
[cppreference std::ranges](https://en.cppreference.com/w/cpp/ranges/range)
:::
:::{.callout-note}
Why `std::begin(t)` instead of `t.begin()`?
:::
## Ranges: Pipelining
```cpp
C(B)
B | C
```
- Views can be chained by overloading the `operator|`
(see [CompilerExplorer](https://godbolt.org/z/7hvYnrbWa)).
```cpp
auto const data = {0, 1, 2, 3, 4, 5};
auto even = [](const auto& v) { return 0 == v % 2; };
auto square = [](const auto& v) { return v * v; };
// "pipe" syntax of composing the views:
auto result { data
| std::views::filter(even)
| std::views::transform(square)
| std::views::drop(2)
| std::views::reverse
| std::views::transform([](const auto& v){ return std::to_string(v); }) };
```
## Ranges: views
:::{.callout-tip icon=false}
## Eric Niebler
"Views are composable adaptations of ranges where the adaptation happens lazily as the view is iterated."
:::
```cpp
template<class D>
requires std::is_class_v<D> && std::same_as<D, std::remove_cv_t<D>>
class view_interface;
```
`view_interface` is typically used with [CRTP](https://godbolt.org/z/4G77YKf1z)
```cpp
class my_view : public std::ranges::view_interface<my_view> {
public:
auto begin() const { /*...*/ }
auto end() const { /*...*/ }
};
```
## Ranges: Lazy Evaluation
```cpp
auto odd = [](int i){ return i % 2 == 1; };
auto isPrime = [](int i) {
for (int j=2; j*j <= i; ++j){
if (i % j == 0) return false;
}
return true;
};
for (int i: std::views::iota(1) | std::views::filter(odd)
| std::views::filter(isPrime)
| std::views::take(10))
{
std::cout << i << std::endl;
}
```
- Expression templates
- [CompilerExplorer transform](https://godbolt.org/z/fEnKGoK7f)
## C++20: Text Formating
- `std::format`
- Safe and extensible
- Faster then printf and iostreams
- Separation of format string and arguments
```cpp
std::format("The answer is {}.", 42);
std::format("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
```
- Available at [{fmt}](https://github.com/fmtlib/fmt) until compiler support
[![](images/godbolt-icon.svg){height=40}
Exercise](https://godbolt.org/z/Psoavhbc4)
## Comparison before C++20
- 6 comparison operators
- `==`, `<` contain the real logic
- `!=`, `>`, `<=`, `>=` will be derived
- Free functions to allow comparison of convertible types
- 18 comparison operators for non-convertible types
- `op(const& T1, const& T2)`
- `op(const& T2, const& T1)`
[![](images/godbolt-icon.svg){height=40}
Exercise](https://godbolt.org/z/8qj6vx1hf)
::: notes
- Write a 2-dim. point class with all comparison operators
- Show free function
- Write same class with spaceship operator
:::
## Comparison before C++20
```cpp
struct Point
{
int x,y;
friend bool operator == (const Point& a, const Point& b) {
return a.x == b.x and a.y == b.y; }
friend bool operator < (const Point& a, const Point& b) {
return a.x < b.x or (a.x == b.x and a.y < b.y); }
friend bool operator != (const Point& a, const Point& b) {
return !(a==b); }
friend bool operator <= (const Point& a, const Point& b) {
return !(b<a); }
friend bool operator > (const Point& a, const Point& b) {
return b<a; }
friend bool operator >= (const Point& a, const Point& b) {
return !(a<b); }
};
```
## C++20: Three-way Comparison
- Spaceship operator `<=>` (similar to `strcmp`)
- (a <=> b) < 0 if a < b
- (a <=> b) > 0 if a > b
- (a <=> b) == 0 if a == b
- Compiler generates all 6 comparison operators to compare X with Y memberwise
```cpp
auto X:: operator<=>(const Y&) const = default;
```
- Custom implementation needs also `operator ==`
## Comparison Categories {.smaller}
- `strong_ordering`
- exactly one of `<, >, ==` must be true and if `a == b` then `f(a) == f(b)`
- `weak_ordering` (equivalent but not equal)
- exactly one of `<, >, ==` must be true and if `a == b` then `f(a) != f(b)`
- Example: `CaseInsensitiveString` storing original string, but compare in case-insensitive way.
- `partial_ordering`
- one of `<, >, ==` might be true and if `a==b` then `f(a) != f(b)`
- Example: float/double because `NaN` is not comparable
## Coding Competition
[GoogleCodeJam](https://codingcompetitions.withgoogle.com/codejam)
2016 Quali Round Problem B: Revenge of the Pancakes
Stack of pancakes with a happy face made of chocolate on one side '+' and nothing on the other side '-'. Goal is to have all pancakes with the happy side on the top.
[![](images/godbolt-icon.svg){height=40}
Here we go!](https://godbolt.org/z/jc8TocKMn)
## Coding Competition Solution {.smaller}
```cpp
std::string stack{"++--+-"};
auto flip = [](const char c){
return c == '+' ? '-' : '+'; // Conditional/Ternary operator
};
int n = 0;
for (auto first = std::ranges::find(stack, '-'); first != std::end(stack);
first = std::ranges::find(stack, '-'), n++)
{
if (stack[0] == '+') {
auto sub = std::ranges::subrange(std::begin(stack), first);
std::ranges::transform(sub, std::begin(sub), flip);
} else {
auto first_happy = std::ranges::find(stack, '+');
auto sub = std::ranges::subrange(std::begin(stack), first_happy);
std::ranges::transform(sub, std::begin(sub), flip);
}
}
std::cout << "You need " << n << " flips to make all happy." << std::endl;
```
[![](images/godbolt-icon.svg){height=40}
Exercise](https://godbolt.org/z/8jKWfGY59)
::: notes
Solution: 74 flips
:::
## Easier Exercise
- Print the first 10 prime numbers
```cpp
auto isPrime = [](int i) {
for (int j=2; j*j <= i; ++j){
if (i % j == 0) return false;
}
return true;
};
auto primes = // use std::views::iota, std::views::filter, std::views::take(10)
fmt::print("{}\n", primes);
```
[![](images/godbolt-icon.svg){height=40}
Here we go!](https://godbolt.org/z/14MEKKo6z)
[![](images/godbolt-icon.svg){height=40}
Solution](https://godbolt.org/z/sqndT57j3)
## Summary
- C++20 is like C++11 a major change in the language
- The Big Four of C++20
- `Ranges` is a great step towards functional programming
- `Modules` simplifies multiple translation units
- `Concepts` allows template arguments specifications
- `Coroutines` are stackless and can be suspended
- `Reflections` and more ranges are expected for C++23
## Thank you {.center}
:::{.callout-tip icon=false}
## Bjarne Stroustrup
"Within C++, there is a much smaller and cleaner language struggling to get out"
:::