-
Notifications
You must be signed in to change notification settings - Fork 1
/
modern-cplusplus.html
8015 lines (5422 loc) · 192 KB
/
modern-cplusplus.html
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++ - C++11/14/17 Extensions</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++
Focusing
* C++11/14/17 Extensions
© 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)
* [Some useful stuff ](#some_useful_stuff)
* [`const` vs. `constexpr` ](#const_vs_constexpr)
* [Type-Dependant Coding ](#type_dependant_coding)
* [New Kinds of Literals ](#new_kinds_of_literals)
* [Strongly Typed Enumerations ](#strongly_typed_enums)
* [Copying vs. Moving ](#copying_vs_moving)
* [New Meaning of `auto` ](#new_meaning_of_auto)
* [Uniform Initialisation ](#uniform_initialisation)
* [Range Based Loops ](#range_based_loops)
* [Lambdas (Function Literals) ](#lambdas)
* [Operations on Callables ](#operations_on_callables)
* [Features for Classes ](#features_for_classes)
* [STL-Extensions ](#stl_extensions)
* [Smart Pointers ](#smart_pointers)
* [Date and Time ](#date_and_time)
* [Regular Expressions ](#regular_expressions)
* [Random Numbers ](#random_numbers)
* [`noexcept` ](#noexcept)
* [Multi-Threading ](#multi_threading)
* [Experimental Features ](#experimental_features)
------------------------------------------------------------
---
------------------------------------------------------------
* Example: modern_cplusplus/demo.cpp
* Example: preprocessor_macro/demo.cpp
* Example: pxt.h
* Example: show_type/demo.cpp
* Example: decltype/demo.cpp
* Example: const_usage/demo.cpp
* Example: const_object/demo.cpp
* Example: constexpr/demo.cpp
* Example: constexpr_ctor/demo.cpp
* Example: raw_string_literal/demo.cpp
* Example: enumeration/demo.cpp
* Example: value_semantics/demo.cpp
* Example: reference_basics/demo.cpp
* Example: copy_move_basics/demo.cpp
* Example: copy_move_defaults/demo.cpp
* Example: move_only_types/demo.cpp
* Example: perfect_forwarding/demo.cpp
* Example: auto_variables/demo.cpp
* Example: auto_typed_functions/demo.cpp
* Example: init_syntax/demo.cpp
* Example: initializer_lists/demo.cpp
* Example: range_for/demo.cpp
------------------------------------------------------------
---
------------------------------------------------------------
* Example: callable_lambda/demo.cpp
* Example: callable_operation/demo.cpp
* Example: member_init/demo.cpp
* Example: override_final/demo.cpp
* Example: template_variable/demo.cpp
* Example: unique_pointer/demo.cpp
* Example: shared_pointer/demo.cpp
* Example: shared_from_this/demo.cpp
* Example: weak_pointer/demo.cpp
* Example: chrono_library/demo.cpp
* Example: chrono_duration/demo.cpp
* Example: chrono_clocks/demo.cpp
* Example: chrono_timepoints/demo.cpp
* Example: regular_expressions/demo.cpp
* Example: random_numbers/demo.cpp
* Example: tuple_demo.cpp
* Example: string_related/demo.cpp
* Example: noexcept_usage/demo.cpp
------------------------------------------------------------
---
name: notice_to_the_reader
## Notice to the Reader
* This document supplies the **Guiding Thread** only
- It is not meant to be read stand alone
- The bulk of teaching material is in the
[live demos](#live_examples)
- created and augmented throughout this course, while
- **YOU** (the listeners) control for each topic
- the depth of coverage and
- the time spent on it
* In the *Electronic Version* feel free to follow the
[reference links](#linked_reference_documentation)
* 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++17 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!**
---
### Ways to Learn "Modern C++"
* Assuming you are well versed in "Classic C++98"
- Get the idea from an example
- Look-up the reference documentation
- Grasp what you (seem to) understand at from a cursory look
- **Test your understanding by tweaking the example!**
- Maybe go back to documentation …
- … but do not loop endlessly
--------------------------------------------------------------------------------
Most language features and library classes in C++ are designed to work exactly
as you would expect it … except those that work differently.._[]
.F[:
According to information theory the latter ones, i.e. areas you find surprising,
contribute more to the "amount" you learned as those where everything behaves
according to your expectations.
]
---
name: linked_reference_documentation
### Linked Reference Documentation
* This presentation frequently links to http://en.cppreference.com
- It is provided freely
- It is "vitally alive" and very recent
- It clearly marks additions of C++11, C++14, and C++17
- It provides compilable examples
* A close competitor also to recommend is http://www.cplusplus.com
--------------------------------------------------------------------------------
What if `cppreference.com` goes out of service some day,
temporarily or permanently?
**Well, then the links in this document will not work anymore.**
**But:** There exist mirrors "out there" in the world-wide-web with
static copies and because this presentation is based on [Remark]
it is plain (markdown) text you can load it into any decent editor
and change the link targets systematically. (You can even make a
static copy of the reference site yourself, only the live examples
cannot be compiled then.)
[Remark]: http://remarkjs.com
---
##### Example: modern_cplusplus/demo.cpp
```
#if 1
constexpr int faculty(int n) {
return (n == 0) ? 1 : n*faculty(n-1);
}
#else
using ULL = unsigned long long;
std::function<ULL (ULL)> faculty =
[](ULL n) -> ULL { return n ? n*faculty(n-1) : 1uLL; };
#endif
auto foo(bool tf) /* -> const int* */ {
static constexpr int x{faculty(6)};
return tf ? &x : nullptr;
//if (tf) return &x; else return nullptr;
}
```
http://coliru.stacked-crooked.com/a/8257d868776840dd
* Alternatives in examples are provided to be tried!
- Switch between `#if` – `#else` – `#endif` sections.
- Remove comments (like around `/* -> const int* */`.
- Move comments (like between last two lines in `foo`).
* Add annotations and feel free to extend.
---
##### Example (cont.): modern_cplusplus/demo.cpp
```
#define PX(x)\
do { using namespace std;\
cout << #x " --> " << (x) << endl;\
} while (false)
#include <boost/type_index.hpp>
#define PT(t)\
do { using namespace std; namespace bm = boost::typeindex;\
cout << #t " --> " << bm::type_id_with_cvr<t>() << endl;\
} while (false)
int main() {
PX(faculty(6));
PT(decltype(foo(true)));
}
```
* Useful helpers for writing test `main` programs:
- Simple expression printer macro (`PX`)
- [Boost.Type_index] based type printer macro (`PT`)
[Boost.Type_index]: http://www.boost.org/doc/libs/master/doc/html/boost_typeindex/getting_started.html
---
name: live_examples
### Live Examples (Using Coliru)
* Coliru is provided freely - do not overly stress it!
- It is an Online Compile Service
- Very up-to-date with respect to modern C++
- Includes recent version of Boost Libraries
* **Coliru is provided freely - do not overly stress it!**
-------------------------------------------------------------------------------
Consider to copy the code from the ([Coliru]) example and try it on your
locally installed compiler.
Advantage: you may not be trapped by "Modern C++" features not (yet) supported
by your production use compiler.
Turn to [Coliru] (or another online compile service) only in case of problems
with your local compiler.._[]
.F[:
If you come to the conclusion [Coliru] – or some other free online compile
service is a real big boon consider to make a donation to its provider.
]
[Coliru]: http://coliru.stacked-crooked.com
---
name: some_useful_stuff
## Some Useful Stuff
* [Why - **not** - Use The Preprocessor](#the_preprocessor)
* [Expressions have **Value** and **Type**](#types_vs_values)
* [Printing Types at Run-Time](#show_expression_type)
* [C++98 and C++11 Support (for the former)](#typeid_and_decltype)
* [The Preprocessor (once more)](#the_preprocessor_again)
---
name: the_preprocessor
### The Preprocessor
* Basic Features
- Including Files
- Expanding Macros
- Conditional Compilation
http://en.cppreference.com/w/c/preprocessor
---
#### Preprocessor: `#include` Principles
* Insert contents of a file
- Usually looked up in search path
- May actually skip content (Guard-Technique!)
* File existence can be tested in C++1z
- `__has_include()`
http://en.cppreference.com/w/cpp/preprocessor/include
---
#### Preprocessor: `#include` Problems
* `#include` processing may be time consuming …
- … and even cause subtle problems …
- … especially when unnecessarily duplicated
* Counter measures are:
- External to Compiler: Include guards
- Internal in Compiler: Processing optimisations
---------------------------------------------------
Optimisations and other techniques to improve the "user experience"
are in general not covered by the C++ standardisation but instead
considered a *Quality of Implementation* issue (QOI).
---
#### Preprocessor: `#define` Principles
* Allows textual substitutions
- At early translation phase
- Little regard to C++ syntax
* Caller may provide arguments
http://en.cppreference.com/w/cpp/preprocessor/replace
---
##### Example: preprocessor_macro/demo.cpp
```
#include <cmath>
#include <iostream>
#define PI 3.1415
#define sq(x) x*x
int main() {
double r = 3.0, h = 4.0;
std::cout << r * std::sqrt(sq(r) + sq(h)) * PI << std::endl;
}
```
* Describe what this code does.
* Point-out potential problems.
---
#### Preprocessor: `#define` Problems
* `#define`-s are
- not properly scoped
- may cause code duplication
* `#define`-s expand arguments textually
- Countermeasure: extensive parenthesizing
- **Strictly to avoid: side effects**
* Sloppy use may cause glitches hard to find
---
##### Example (cont.): preprocessor_macro/demo.cpp
```
#include <cmath>
#include <iostream>
#define PI 3.1415
#define sq(x) x*x
namespace my {
inline double sq(double x) { return x*x; }
}
int main() {
using namespace my;
std::cout << sq(PI) << std::endl;
// -- more will be demonstrated live
}
```
* Demonstrate current problems of **macro** version of `sq`
* Add potential improvements
* Point out limits of solution
---
#### Preprocessor: `#if` (etc.) Principles
* Allows to enable or disable parts of a source code
- Conditions limited to:
- Defined preprocessor macro
- Literal constant expressions
- May be nested but not across files
http://en.cppreference.com/w/cpp/preprocessor/conditional
---
#### Preprocessor: `#if` (etc.) Problems
* Conditions evaluated early in translation, e.g.
- no knowledge about types
- conditions need to be trivial
* If used in nested forms
- Code quickly gets unmaintainable
- More so when crossing runtime control structure
```
if (x > 0) { // x is positive
…
#ifdef HANDLE_BELOW_ZERO
} else if (x < 0) { // x is negative
…
#endif
} else { // x is zero or negative
…
}
```
---
#### Preprocessor: `#error` Principles and Problems
* Terminates translation with error message
- Obviously needs to be combined with `#if` (etc.)
* Conditions evaluated early in translation, e.g.
- no knowledge about types
- conditions need to be trivial
http://en.cppreference.com/w/cpp/preprocessor/error
----------------------------------------------------
Consider replacing with `static_assert`
http://en.cppreference.com/w/cpp/language/static_assert
---
##### Optional Example: static_assert/demo.cpp
```
#if __cplusplus < 201402L
#error "This code makes use of C++14 features"
#endif
namespace my {
class first {};
class other : first {};
}
#include <type_traits>
int main() {
static_assert(std::is_convertible<my::other, my::first>{}(),
"my::other must be convertible in my::first");
}
```
http://coliru.stacked-crooked.com/a/cf6cfccb737c9c1b
-----------------------------------------------------------------
The above makes use of language features not covered so far and
is meant for demonstration purposes only. (Expert question: Which
C++14 feature is actually used and how could it have been avoided?)
---
#### Preprocessor: Classic Uses
* Including Files
* Include Guards
--------------------------------
* Alternative `#pragma once`:
- Widely Supported
- Not Standardized
---
##### Example: pxt.h
```
// file: pxt.h
#ifndef PXT_H
#define PXT_H
#include <iostream>
#define PX(expr)\
((void)(std::cout << (expr) << std::endl))
#endif
```
```
// file: preprocessor_macro/demo.cpp
#include "../pxt.h"
int main() {
PX(6*7);
}
```
http://coliru.stacked-crooked.com/a/3fc20b0a0765e6fb
* Improve macro to also show the expression textually.
* Also include file name and line number where called.
---
#### Preprocessor: Deprecated Uses
* Macros to centralize literals
- Prefer `const` / `constexpr`
* Macros to avoid subroutines
- Prefer `inline`
* Macros to parametrize types
- Prefer `template`-s
* Complex conditional sections
- Rely on "optimised-out" Run-Time `if`
- Consider Template Meta-Programming
---
##### Example (cont.): preprocessor_macro/demo.cpp
```
…
namespace my {
const double PI = 2*std::acos(0.0);
inline double sq(double x) { return x*x; }
}
…
int main() {
using namespace my;
PX(1/PI);
…
int z = 9;
PX(++z);
…
}
```
http://coliru.stacked-crooked.com/a/eadcb46a3f2391fa
* Come up with more test cases.
---
##### Example (cont.): preprocessor_macro/demo.cpp
```
…
namespace my {
…
const/*expr*/ double PI = 2*std::acos(0.0);
#if 0
inline constexpr double sq(double x) { return x*x; }
#else
template<typename T>
inline constexpr T sq(T x) { return x*x; }
#endif
…
}
…
```
http://coliru.stacked-crooked.com/a/006fb9bec1154bf8
---------------------------------------------------------
Covered later:
* Difference between `const` and `constexpr`.
* Fully type-generic version of `sq`.
---
#### Preprocessor: Macros Still Useful
* Adorned use of macro arguments
- Stringizing (`#arg`)
- Token Pasting (`arg ## whatever`)
---
##### Example: pxt.h
```
#define PX(expr)\
((void)(std::cout << __FILE__ << ':' << __LINE__\
<< "\t" #expr " --> "\
<< (expr) << std::endl))
```
http://coliru.stacked-crooked.com/a/429608d619fa9559
---------------------------------------------------
Some more examples are shown along this chapter.
---
name: types_vs_values
### Types vs. Values
* Each expression has distinct
- **Type** – known at Compile-Time
- **Value** – known at Runtime
---
#### Show Expression Value
* At Run-Time `operator<<` works for
- **All** basic types
- **Some** more complex types
* e.g. pointers (shows address in hex)
* **not** for native arrays
* Can be overloaded for user-defined classes
* Values often **not** known at Compile-Time
---
##### Optional Example: show_value/demo.cpp
* Overload output operator for class `my::point`.
* Advanced: overload output operator for native array.
---
name: show_expression_type
#### Show (Expression) Type
* At Run-Time
- … ?
* At Compile-Time
- May occurs in error messages
* Types are **always** known at Compile-Time
---
##### Example: show_type/demo.cpp
```
#define PX(value)\
std::cout << value << std::endl
#define PT(type)\
std::cout << ?…? type ?…? << std::endl
int main() {
int v = 6*7;
PX(v); // --> 42
PT(int); // --> int
}
```
* How could that be achieved?
---
name: type_aliases
### Type Aliases
* Alternative syntax for `typedef`
- After keyword `using` alias name comes first …
- … then an equals (`=`), then the aliased type
* Improves readability
- left to right, as with variables
- otherwise same semantics as `typedef`
* In addition: may be templated
http://en.cppreference.com/w/cpp/language/type_alias
---
##### Example (cont.): show_type/demo.cpp
```
int main() {
using iptr = int*;
typedef double *dptr;
PT(iptr); // --> int*
PT(dptr); // --> double*
}
```
---
name: typeid_and_decltype
### `typeid()` and `decltype()`
* C++98 introduced `typeid()`
- Has `name()` member (among other uses)
- Returns unique string for each distinct type
- Name of type may be encoded (not C++ syntax)
http://en.cppreference.com/w/cpp/language/typeid
* C++11 added `decltype()`
- Takes type for expression
- and then ???
http://en.cppreference.com/w/cpp/language/decltype
---
##### Example (cont.): show_type/demo.cpp
```
#include <iostream>
#include <typeinfo>
#define PT(type)\
std::cout << typeid(type).name() << std::endl
int main() {
using iptr = int*;
iptr p = nullptr;
PT(int);
PT(iptr);
PT(decltype(p));
PT(decltype(*p));
PT(decltype(nullptr));
}
```
http://coliru.stacked-crooked.com/a/f444d6912e498e68
* Can you guess the name mangling?
---
#### Show Type in C++ Syntax
* Maybe your Compiler does (lucky you!) …
* … if not:
- Read in error message
- idea "stolen" from Scott Meyers
- ugly … but works (for desperadoes!)
- Turn error message into string
- starts out simple …
- … needs much diligence to complete
---
##### Example (cont.): show_type/demo.cpp
```
template<typename T> struct showtype;
template<> struct showtype<int> {
static const char *str() { return "int"; }
};
template<> struct showtype<int*> {
static const char *str() { return "int*"; }
};
#define PT(type) std::cout << #type << " --> "\
<< showtype<type>::str() << std::endl;
int main() {
int* p = nullptr;
PT(int);
PT(decltype(p));
// PT(decltype(*p));
}
```
http://coliru.stacked-crooked.com/a/62bc674eba5a575c
* Why is `decltype(p)` an error?
* What to add so that it can be printed?
---
#### Build Your Own Type Printer
* The Preprocessor is your friend
* Or use Boost.Type_index
---
##### Example (cont.): show_type/demo.cpp
```
…
template<> struct showtype<void>
{static std::string str() {return "void";}};
template<> struct showtype<bool>
{static std::string str() {return "bool";}};
…
template<> struct showtype<unsigned long long>
{static std::string str() {return "unsigned long long";}};
…
template<typename T> struct showtype<const T>
{static std::string str() {return "const " + showtype<T>::str();}};
…
template<typename T> struct showtype<T*>
{static std::string str() {return showtype<T>::str() + "*";}};
template<typename T> struct showtype<T&>
{static std::string str() {return showtype<T>::str() + "&";}};
…
```
http://coliru.stacked-crooked.com/a/4907e3cbb1ed8c81