-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemplate-cplusplus.html
More file actions
2378 lines (1636 loc) · 58.3 KB
/
template-cplusplus.html
File metadata and controls
2378 lines (1636 loc) · 58.3 KB
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>Modern C++ - Meta-Programming</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<!-- when changing the stylesheet file please see also remark below -->
<link rel="stylesheet" type="text/css" href="styling.css" />
</head>
<body>
<!-- :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->
<!-- :::::::::: template pages come first ... skip to REALCONTENT ::::::::: -->
<!-- :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->
<textarea id="source">
layout: true
name: blank
styling: styling.css
styling-by: Martin Weitzel
<!--
*****************************************************************************
Template used for title page (only)
*****************************************************************************
Please change the 'styling-by:' attribute if you change the style-sheet.
-->
.stylehint[
Styled with [{{styling}}]({{styling}}) by {{styling-by}}
]
---
layout: true
name: plain
copyright: (CC) BY-SA
branding: [Dipl.-Ing. Martin Weitzel](http://tbfe.de)
customer: [für MicroConsult Training & Consulting GmbH](http://microconsult.de)
<!--
*****************************************************************************
Template used for for pages NOT referring to any Info-Graphic
*****************************************************************************
The following attributes are mandatory FOR THE TEMPLATE PAGE and should
simply be left empty if not meaningful.
copyright: will be reproduced in each page footer first
branding: will reproduced in each page footer next
customer: will be reproduced in each page footer last
As the above attributes are part of several page templates a global replace
should be used for consistent changes.
On pages USING THIS TEMPLATE the following attributes must be set:
header: ## and header text (i.e. including the markdown formatting indicator)
-->
.pagefooter[
{{copyright}}: {{branding}} {{customer}} .microconsult-logo[]
]
<!-- :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->
<!-- end of templates ... below comes the REALCONTENT - TNETNOCLAER ends it -->
<!-- :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->
---
template: blank
# Agenda: Modern C++
Focussing
* Template Meta-Programming
© 2019: [Creative Commons BY-SA]
* by: [Dipl.-Ing. Martin Weitzel](http://tbfe.de)
* for: [MicroConsult GmbH Munich](http://microconsult.com)
[Creative Commons BY-SA]: https://creativecommons.org/licenses/by-sa/4.0/
---
------------------------------------------------------------------
* [Notice to the Reader ](#notice_to_the_reader)
* [Template Basics ](#template_basics)
* [Meta-Programming ](#meta_programming)
* [Type Traits ](#type_traits)
* [Applying SFINAE ](#applying_sfinae)
* [Variadic Templates ](#variadic_templates)
* [Concepts Light ](#concepts_light)
------------------------------------------------------------------
* Example: template_class/demo.cpp
* Example: template_function/demo.cpp
* Example: meta_programming/demo.cpp
* Example: type_calculation/demo.cpp
* Example: value_calculation/demo.cpp
* Example: type_traits/demo.cpp
* Example: function_sfinae/demo.cpp
* Example: class_sfinae/demo.cpp
* Example: parameter_pack/demo.cpp
* Example: variadic_function/demo.cpp
* Example: my_tuple/demo.cpp
------------------------------------------------------------------
---
## Notice to the Reader
* This document supplies the **Guiding Thread** only
- It is not recommended to be read it "as-is" stand alone
- The bulk of teaching material is in the live demos
- created and augmented throughout this course, while
- **YOU** – the participants - control for each topic
- the depth of coverage and
- the time spent on it
* In the electronic version feel free to follow the links
* The Printed version is provided for annotations in hand-writing
-------------------------------------------------------------------
If you nevertheless want to use this document for self-study, not
only to follow the links to the compilable code, **also vary and
extend it**.
---
If you need suggestions what to try (add or modify) you will find
some in this presentation and a lot more usually in the example
code itself.
There are two basic forms:
* **Conditional code `#if … #else … #endif`**
- Usually both versions work, demonstrating alternative ways to
solve the particular problem at hand
- Sometimes not all versions are compatible with C++11 but may
require C++14 or even C++14 features
* **Commented-out lines – sometimes with alternatives**
- Sometimes these are shown because they **do not compile** and
should indicate that a particular solution that may even seem
attractive at first glance is **not** the way to go.
- Furthermore, if removing the comment often some other line
(in close proximity, typically the previous or next one) needs
to be commented.
**Understanding the code by trying variations is the crucial step
to actually internalise the topics covered!**
---
name: template_basics
## Template Basics
* [Class Templates ](#class_templates)
* [Function Templates ](#function_templates)
---
name: class_templates
### Class Templates
* Originally designed for type-generic container classes
- At Implementation-Time there is a **definition**
- At Compile-Time **instantiation** follows
http://en.cppreference.com/w/cpp/language/class_template
---
#### Class Template Definition
* At Implementation-Time:
- Keep some type(s) generic
- Keep some value(s) generic
* Much like regular class …
- … starting with template argument list
---
##### Example: template_class/demo.cpp
```
class point {
double xc, yc;
public:
point(double xc_, double yc_) : xc(xc_), yc(yc_) {}
double x() const {return xc;}
double y() const {return yc;}
double x(double x_) {return xc = x_;}
double y(double y_) {return yc = y_;}
point shifted(double xdelta, double ydelta) const;
};
point point::shifted(double xd, double yd) const {
return {xc + xd, yc + yd};
}
```
http://coliru.stacked-crooked.com/a/f9b919a12f39f613
* How to parametrize the type of `xc`, and `yc`?
---
##### Example (cont.): template_class/demo.cpp
```
template<typename T>
class point {
T xc, yc;
public:
point(T xc_, T yc_) : xc(xc_), yc(yc_) {}
T x() const {return xc;}
// ...
};
template<std::size_t N>
class fstring {
char fs[N+1];
void copy(const char* cp) {std::strncpy(fs, cp, N)[N] = '\0';}
public:
fstring(const char *init) {copy(init);}
fstring& operator=(const fstring& rhs) {copy(rhs.fs);
return *this;}
// ...
};
```
* Which of the both classes above templates a type?
* which a compile time constant?
* Could both be combined?
* (For which of both classes would that perhaps make sense?)
---
#### Class Template Instantiation
* Concrete template arguments **must** be supplied on instantiation
- Class name should be thought "including" concrete types, i.e.
- Same template with different arguments denote different classes
---
##### Example (cont.): template_class/demo.cpp
```
template<typename T>
class point {
T xc, yc;
public:
point(T xc_, T yc_) : xc(xc_), yc(yc_) {}
T x() const {return xc;}
// ...
T y(T y_) {return yc = y_;}
point shifted(T xd, T yd) const;
};
template<typename T>
point<T> point<T>::shifted(T xd, T yd) const {
return {xc + xd, yc + yd};
}
int main() {
point<double> a{3.5, 7.0};
point<int> c{10, 20};
// ...
}
```
* How are arguments transfered – by value or by reference?
* (What if the instantiation type of `point` were *move only*?)
---
#### Class Template Specialisation
* Existing *Primary Templates* may be specialised
* Syntactically recognized:
- Angle brackets follow class name in definition …
- … holding argument list **identical** to primary template
- "Outer" argument list must be different ("specialise" something):
- Empty for a full specialisation
- Otherwise holds names for deduction
* **Compiler selects "most specialised" matching version**
http://en.cppreference.com/w/cpp/language/template_specialization
http://en.cppreference.com/w/cpp/language/partial_specialization
---
##### Example (cont.): template_class/demo.cpp
```
template<typename T> struct tp;
template<> struct tp<int>
{static std::string str() {return "int";}};
template<typename T> struct tp<T*>
{static std::string str() {return tp<T>::str() + "*";}};
template<typename T> struct tp<const T>
{static std::string str() {return "const " + tp<T>::str();}};
int main() {
PX(tp<int>::str());
PX(tp<double>::str());
int i = 42;
PX(tp<decltype(i)>::str());
PX(tp<decltype(&i)>::str());
int cri = i;
PX(tp<decltype(cri)>::str());
}
```
* Identify the *Primary Template* in the code above.
* Identify its *Full* and *Partial* Specialisations.
* Further flesh-out the code to make it usable for the examples.
---
### Function Templates
* Originally designed for type-generic algorithms
http://en.cppreference.com/w/cpp/language/function_template
---
#### Function Template Definition
* At Implementation-Time:
- Keep some type(s) generic (typical)
- Keep some value(s) generic (rare but possible)
* Much like regular function …
… but starts with template argument list
---
##### Example: template_function/demo.cpp
First version:
```
template<typename T>
T square(const T& arg) {
return arg*arg;
}
```
Second version:
```
template<typename T>
auto square(const T& arg) -> decltype(arg*arg) {
return arg*arg;
}
```
http://coliru.stacked-crooked.com/a/08d2a5bf1ceffd78
* Describe what is different between both versions of `square`.
* Under which circumstances may this become visible to the caller?
* Is it wise handing over arguments per reference for **all** types?
* (How might the latter be changed for **some** types?)
---
#### Function Template Instantiation
* Concrete argument values **may** be supplied …
* … but more often are deduced from call arguments
- Generic name in argument list may be adorned
- **Be sure to understand what exactly is deduced**._[]
.pull-left[
```
template<typename T>
void foo(T arg) {
… // type of `T` same
… // as type of `arg`
}
template<typename T>
void bar(const T& arg) {
… // what is the type
… // of `arg` here ...?
… // NOT same as `T`!
}
```
]
.pull-right[
Assume calls like:
```
int i = 10;
foo(i); bar(i);
const int k = 20;
foo(k); bar(k);
foo(std::atof("10.1"));
bar(std::atof("10.2"));
```
]
.F[:
Type deduction for template arguents is not limited to trvial or
close to trial cases as is shown in the examples given here:
http://coliru.stacked-crooked.com/a/96c78740a1c689f5
]
---
##### Example (cont.): template_function/demo.cpp
```
int main() {
PX(square(2)); PX(square<double>(2));
PX(square(2.5)); PX(square<int>(2.5));
// PX(square(false)); PT(decltype(square(false)));
// PX(square(true)); PT(decltype(square(true)));
// PX(square<double>(true));
}
```
* Predict the output of the above code.
* Will the currently commented-out lines compile too?
* Or not all but some?
* (If so, what output do you expect?)
---
#### Function Template Overloading
* Function templates may be overloaded by non-templates
- **Exactly matching overloads get always preferred**
* In addition there may also be templated overloads
- If any, the "closest match" gets selected …
- **… or Compile-Error if not unique**
* Finally, function templates may also be **fully** specialised
http://en.cppreference.com/w/cpp/language/overload_resolution
http://en.cppreference.com/w/cpp/language/template_specialization
-----------------------------------------------------------
Note: there is no syntax for partial specialisation of function
templates – maybe because the rules are complicated enough even
without … :-/
http://www.gotw.ca/gotw/049.htm
---
##### Example (cont.): template_function/demo.cpp
```
template<typename T>
auto square(const T& arg) -> decltype(arg*arg) {
return arg*arg;
}
auto square(bool arg) -> bool {
return arg;
}
int main() {
PX(square(false)); PT(decltype(square(false)));
PX(square(true)); PT(decltype(square(true)));
PX(square<double>(true));
}
```
* Why is it that both versions of `square` can coexist?
* Will the existence of the second version change the output?
---
name: meta_programming
## Meta-Programming
* The key insight is:
- any instantiation of a template requires that
- the compiler carries out some internal calculation
---
##### Example: meta_programming/demo.cpp
```
// template definitions for `add_ptr`, `remove_ptr`,
// and `remove_all_ptr` shown and explained later
int main() {
// equivalent to:
… my::add_ptr<int>::type …
// ^^^^^^^^^^^^^^^^^^^^^^------------ type `int*`
… my::remove_ptr<int**>::type
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^------- type `int*`
… my::remove_all_ptr<int***>::type …
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- type `int`
… my::countbits<42>::value …
// ^^^^^^^^^^^^^^^^^^^^^^^^---------- value `42`
}
```
http://coliru.stacked-crooked.com/a/e926a38155979659
* Where's the "meta" – can you see it?
* Understand that all "calculations" happen at *Compile Time*.
* Why is appending the `::type` or `::value` part absolutely essential?
---
### Meta-Programming Basics
* The C++ template system is a full programming language …
- … yet often not the most convenient one
- (at least given for what it was used in the past)
* But inconvenience is at the site of the implementor …
- … to ease the work of its clients
- **except for messy error messages**
---------------------------------------------------------
Be sure to understand: anything talked about with respect to
Meta-Programming means things that happen at Compile-Time,
though often an executable program needs to be created too,
but simply to show the effect.
---
##### Example (cont.): meta_programming/demo.cpp
```
template<typename T>
struct add_ptr {using type = T*;};
template<typename T> struct remove_ptr;
template<typename T>
struct remove_ptr<T*> {using type = T;};
template<typename T> struct remove_all_ptr {using type = T;};
template<typename T> struct remove_all_ptr<T*> {
using type = typename remove_all_ptr<T>::type;
};
template<unsigned N>
struct countbits {
static const std::size_t value = (N & 0x1)
+ countbits<(N>>1)>::value;
};
template<>
struct countbits<unsigned{0}> {
static const std::size_t value = 0;
};
```
* Identify the *Meta Functions* above and their arguments.
* How are they are getting "called" and what do they return?
---
#### Types as Meta-Programming Input and Output
* Any "input" to a meta program is
- either a type
- or a value
* Needs to explicitly stated somewhere in the source code
---
##### Example (cont.): meta_programming/demo.cpp
```
int main() {
// ------------------------------------------------ "input" is:
// typeprinter< add_ptr<int>::type > notused;
// ^^^------------------------------ ??
// typeprinter< remove_ptr<int**>::type > notused;
// ^^^^^------------------------- ??
// typeprinter< remove_all_ptr<int***>::type > notused;
// ^^^^^^-------------------- ??
str::cout << countbits<42>::value;
// ^^----------------------------- ??
}
```
* Locate the "input" of each *Meta Function* and determine what it is.
- A type?
- Or a value?
<!-- -->
* Assuming the *Meta Functions* do what their names suggests:
- What is the expected "output"?
- What is the difficulty with showing a type?
---
#### Template Meta-Programming Output
* Any "output" of a meta program is
- "something that can be compiled"
- or an error message
----------------------------------------------------------
For demonstration purposes meta programming often includes a
small program that can be compiled to an executable, showing
the intended effect (e.g. by printing a calculated type).
---
##### Example (cont.): meta_programming/demo.cpp
```
template<typename> struct typeprinter;
int main() {
// ----------------------------------------------- "output" is:
// typeprinter< add_ptr<int>::type > notused;
// ^^^^^^^^^^^^----------------------------- ??
// typeprinter< remove_ptr<int**>::type > notused;
// ^^^^^^^^^^^^^^^^^------------------------ ??
// typeprinter< remove_all_ptr<int***>::type > notused;
// ^^^^^^^^^^^^^^^^^^^^^^------------------- ??
str::cout << countbits<42>::value;
// ^^^^^^^^^^^^^---------------------------- ??
}
```
* How is *Meta Program* "value output" shown in the example above?
* How is *Meta Program* "type output" shown in the example above?
---
#### Digression: Recipe to Implement a Type Printer
* Instead of just defining a variable (`notused`):
- define a full specialisation for `int` …
- … (and any other basic type that may occur) …
- … with a static member returning the type as string value
- add partial specialisations for adorned types …
- … delegating further resolution to recursive calls
---
##### Optional Example (cont.): meta_programming/demo.cpp
```
template<typename> struct typeprinter;
template<> struct typeprinter<int>
{static std::string str() {return "int";}};
// ... and more "mutatis mutandis"
template<typename T> struct typeprinter<T*>
{static std::string str() {return typeprinter<T>::str() + "*";}};
// ... and more "mutatis mutandis"
int main() {
std::cout
<< typeprinter<add_ptr<int>::type>::str() << '\n'
<< typeprinter<remove_ptr<int**>::type>::str() << '\n'
<< typeprinter<remove_all_ptr<int***>::type>::str() << '\n'
<< countbits<42>::value << '\n';
}
```
* For practical purposes consider to wrap output of a
- … type into a macro accepting a type as argument,
- … value into a macro accepting an expression as argument.
-------------------------------------------------------------------
The macros `PT` and `PX` that have been used a lot already do just that.
---
##### Optional Example (cont.): meta_programming/demo.cpp
```
#define PX(expr)\
((void)(std::cout << __FUNCTION__ << ':' << __LINE__\
<< "\t" #expr " --> "\
<< (expr) << std::endl))
#define PT(type)\
((void)(std::cout << __FUNCTION__ << ':' << __LINE__\
<< "\t" #type " --> "\
<< typeprinter<type>::str() << std::endl))
int main() {
PT(add_ptr<int>::type);
PT(remove_ptr<int**>::type);
PT(remove_all_ptr<int***>::type);
PX(countbits<42>::value);
}
```
* Over what was describe so far:
- Which refinement is contained in the macros?
- Why does it makes sense?
- Can you still spot any shortcomings?
---
### Implementation Selection
* Typical meta programming goal is "implementation selection"
- In simple cases with (direct) specialisation
- Alternatively with overloading and SFINAE
* E.g. choose between
- value and reference argument in a function call
- member-wise copy and `std::memcpy` in a container
-----------------------------------------------------------
This page mainly aims to the inpatient who at least want to
have a slight idea where all this "meta …" leads to.
---
#### Template Meta-Programming Functions
* Any template class also constitutes a (meta-) function
- its arguments come from the template argument list
- it is called by instantiating the template
* Calling conventions make sense, e.g. a member
- …`::result` that "calls" the meta function, returning
- *either* a type
- *or* a value
- …`::type` that "calls" the meta function, returning a type
- …`::value` that "calls" the meta function, retuning a value
-----------------------------------------------------------------
Sticking to *one* of the above – i.e. *either* using `::result`
for both, types and values returned, *or* differentiating with
`::type`` and ``::value` – makes a lot of sense, because it
enables "higher order" meta functions (that are meta-functions
which manipulate other meta functions).
---
#### Branches in Meta-Programs
* **All** branching in Meta-Programming
- needs to be done by specialisation
* I.e. there needs to be a primary template …
- … **either** covering the general case …
- … **or** just being declared but not defined …
- … if there are specialisations for all possible cases
---
##### Example (cont.): meta_programming/demo.cpp
```
namespace my {
template<typename T>
struct is_ptr {static const bool value{false};};
template<typename T>
struct is_ptr<T*> {static const bool value{true};};
template<typename T>
struct remove_ptr;
template<typename T>
struct remove_ptr<T*> {using type = T;};
}
int main() {
PX(my::is_ptr<int>::value);
// PT(my::remove_ptr<int>::type);
PX(my::is_ptr<int*>::value);
PT(my::remove_ptr<int*>::type);
int i{42}; PT(my::is_ptr<decltype(i)>::value);
PT(my::remove_ptr<decltype(&i)>::type);
}
```
* Explain branches `my::is_ptr` and `my::remove_ptr`.
* Why does `my::rm_pointer` not work with non-pointers?
* (Feel free to add more meta function test "calls" to the code.)
---
#### Template Meta-Programming Loops
* In C++98 any meta programming loops
- need to resolved to recursion
- terminated by specialisation
------------------------------------------------------------
**Only** for parameter packs (variadic templates) this is
slightly released in C++11 and further generalised to fold
expressions in C++1z.
---
##### Example (cont.): meta_programming/demo.cpp
```
namespace my {
template<typename T>
struct remove_all_ptr {using type = T;};
template<typename T>
struct remove_all_ptr<T*> {
// using type = remove_all_ptr<T>;
using type = typename remove_all_ptr<T>::type;
};
}
int main() {
PT(my::remove_all_ptr<int>::type);
PT(my::remove_all_ptr<int*>::type);
PT(my::remove_all_ptr<int****>::type);
int *p; PT(my::is_ptr<decltype(&p)>::value);
PT(my::remove_all_ptr<decltype(&p)>::type);
}
```
* Explain the loop in `my::remove_all_ptr`.
* What is essential to avoid an infinite loop?
* How does `my::remove_all_ptr` handle non-pointers?
* How does this differ from handling non-pointers in `my::remove_ptr`?
* How to make one pointer level mandatory in `my::remove_all_ptr` too?
* (Why compiles the commented-out flawlessly but still does not work?)
---
### Compile-Time Type Calculations
* Internal calculations may transform types
- There are many practical uses …
- … though mostly not visible at first glance
-------------------------------------------------------------------
Please keep calm, be patient, and follow the examples, even if you
have no idea to where it finally leads.
---
##### Example: type_calculation/demo.cpp
```
template<typename T>
struct fixpoint {
const T x{};
const T y{};
// using argtype = T; // for register-types
using argtype = const T&; // for non-register types
fixpoint(argtype x_, argtype y_)
: x(x_), y(y_) {
PT(argtype);
}
fixpoint shifted(argtype xd, argtype yd) {
PT(argtype);
return {x + xd, y + yd};
}
};
```
http://coliru.stacked-crooked.com/a/8e1d4212337eb36b
* How could `argtype` be defined so that it `automatically` selects
- `T` for types fitting into a register and
- `const T&` for all other types?
You may arbitrarily assume here which types fit into a register, e.g.
`short`, `int`, and `float` do, while `long`, `long long`, `double`,
and `long double` don't.
---
#### Practical Uses of Type Calculations
* Remember: All type calculations
- finally result in implementation selection
- are an and in itself only in simple demo programs
---
##### Example (cont.): type_calculation/demo.cpp
```
template<typename T>
struct argument_type {using type = const T&;};
template<> struct argument_type<short> {using type = short;};
template<> struct argument_type<int> {using type = int;};
template<> struct argument_type<float> {using type = float;};
template<typename T>
struct fixpoint {
const T x{};
const T y{};
using argtype = typename argument_type<T>::type;
fixpoint(argtype x_, argtype y_)
: x(x_), y(y_) {
}
fixpoint shifted(argtype xd, argtype yd) {
PT(argtype);
return {x + xd, y + yd};
}
};