-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.in.html
1168 lines (771 loc) · 20.3 KB
/
index.in.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 lang="en">
<head>
<meta charset="utf-8">
<title>C++ metaprogramming: a paradigm shift</title>
<meta name="author" content="Louis Dionne">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/league.css" id="theme">
<link rel="stylesheet" href="css/custom.css">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<div class="slides">
<section data-markdown=""
data-separator="^====+$"
data-separator-vertical="^----+$"
data-notes="^Note:">
<script type="text/template">
## C++ metaprogramming
<h3 style="opacity: 0.8">a paradigm shift</h3>
<br>
Louis Dionne, C++Now 2015
==============================================================================
## Quadrants of computation in C++
<!--
If needed, define new MathJax commands just below this to avoid seeing
them load on the first slide.
-->
====================
### Runtime computations (classic)
----
### Runtime sequences
```c++
std::vector<int> ints{1, 2, 3, 4};
```
----
### Runtime functions
```c++
std::string f(int i) {
return std::to_string(i * i);
}
std::string nine = f(3);
```
----
### Runtime algorithms
```c++
std::vector<std::string> strings;
std::transform(ints.begin(), ints.end(),
std::back_inserter(strings), f);
```
====================
### `constexpr` computations
----
### `constexpr` sequences
```c++
constexpr std::array<int, 4> ints{1, 2, 3, 4};
```
----
### `constexpr` functions
```c++
constexpr int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
constexpr int six = factorial(3);
```
----
### `constexpr` algorithms
```c++
template <typename T, std::size_t N, typename F>
constexpr std::array<std::result_of_t<F(T)>, N>
transform(std::array<T, N> array, F f) {
// ...
}
constexpr std::array<int, 4> ints{1, 2, 3, 4};
constexpr std::array<int, 4> facts = transform(ints, factorial);
```
====================
### Heterogeneous computations (Fusion)
----
### Heterogeneous sequences
```c++
fusion::vector<int, std::string, float> seq{1, "abc", 3.4f};
```
----
### Heterogeneous functions
```c++
struct to_string {
template <typename T>
std::string operator()(T t) const {
std::stringstream ss;
ss << t;
return ss.str();
}
};
std::string three = to_string{}(3);
std::string pi = to_string{}(3.14159);
```
----
### Heterogeneous algorithms
```c++
fusion::vector<int, std::string, float> seq{1, "abc", 3.4f};
fusion::vector<std::string, std::string, std::string> strings =
fusion::transform(seq, to_string{});
```
====================
### Type-level computations (MPL)
----
### Type-level sequences
```c++
using seq = mpl::vector<int, char, float, void>;
```
----
### Type-level functions
```c++
template <typename T>
struct add_const_pointer {
using type = T const*;
};
using result = add_const_pointer<int>::type;
```
----
### Type-level algorithms
```c++
using seq = mpl::vector<int, char, float, void>;
using pointers = mpl::transform<seq,
mpl::quote1<add_const_pointer>>::type;
```
====================
### Note
```c++
fusion::vector != mpl::vector
```
----
### Consider
```c++
mpl::vector<int, void, char>{} // ok
// error: field has incomplete type void
fusion::vector<int, void, char>{}
```
====================
## Claim
### Type-level $\;\subset\;$ heterogeneous <!-- .element class="fragment" -->
==============================================================================
## Why bother?
Note:
This section contains a couple of motivating examples to pique the curiosity.
The examples should be skimmed over to avoid losing time and explaining
details that will be covered later.
====================
### C++14 is a serious game changer
#### $\rightarrow$ We can do better now
====================
### See for yourself
====================
### Checking for a member: then
%%member-then%%
----
### Checking for a member: soon
%%member-soon%%
----
### Checking for a member: what it should be
%%member-should%%
====================
### Introspection: then
%%introspection-then%%
----
### Introspection: now
%%introspection-now%%
====================
### Generating JSON: then
```c++
// sorry, not going to implement this
```
----
### Generating JSON: now
%%json-usage%%
__Output__:
```json
[1, "c", {"name" : "Joe", "age" : 30}]
```
----
### Handle base types
%%json-base%%
----
### Handle `Sequences`
%%json-Sequence%%
----
### Handle `Structs`
%%json-Struct%%
====================
## Still not convinced?
### Here's more
====================
### Error messages: then
%%error_messages-then%%
```c++
boost/mpl/clear.hpp:29:7: error:
implicit instantiation of undefined template
'boost::mpl::clear_impl<mpl_::integral_c_tag>::apply<mpl_::int_<1> >'
: clear_impl< typename sequence_tag<Sequence>::type >
^
```
----
### Error messages: now
%%error_messages-now%%
```c++
boost/hana/fwd/sequence.hpp:602:13: error:
static_assert failed "hana::reverse(xs) requires xs to be a Sequence"
static_assert(_models<Sequence, typename datatype<Xs>::type>{},
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error_messages.cpp:19:24:
in instantiation of function template specialization
'boost::hana::_reverse::operator()<int>' requested here
auto xs = hana::reverse(1);
^
```
====================
### Compile-times: then and now
<!-- .slide: data-state="haschart" -->
<div class="benchmark-chart" data-dataset="benchmark.including.compile.json"></div>
----
<!-- .slide: data-state="haschart" -->
<div class="benchmark-chart" data-dataset="benchmark.transform.compile.json"></div>
====================
## We must rethink metaprogramming
====================
## But how?
### Here's my take <!-- .element class="fragment fade-in" -->
Note:
Hopefully, the audience should be convinced by now that there's a better way
to write metaprograms. My goal is now to convince them that I found it.
==============================================================================
### What is an `integral_constant`?
```c++
template<class T, T v>
struct integral_constant {
static constexpr T value = v;
typedef T value_type;
typedef integral_constant type;
constexpr operator value_type() const noexcept { return value; }
constexpr value_type operator()() const noexcept { return value; }
};
```
Note:
This section introduces extensions to `std::integral_constant` that follow
the general philosophy of the paradigm shift. I am preparing the grounds for
the next section, which will introduce the type/value unification per-se.
----
### A type-level encoding of a `constexpr` value
```c++
using one = integral_constant<int, 1>;
```
----
### A `constexpr`-preserving object
```c++
template <typename T>
void f(T t) { static_assert(t == 1, ""); }
constexpr int one = 1;
f(one);
// error: t is not constexpr in the body of f
f(integral_constant<int, one>{});
// ok: implicit conversion to int is constexpr
```
Note:
The issue here is that argument passing strips `constexpr`ness. To see it
clearly, consider what would happen if `f` was not a template and if it was
defined in a different translation unit. Inside this other TU, how could the
compiler tell whether the argument `f` is called with is `constexpr` or not?
`constexpr`ness can be retained by encoding the value of the argument in a
type, and then using the template system to pass this value to the body of
the function.
====================
### We can do `constexpr` arithmetic
```c++
constexpr int two = ((3 * 2) + 4) / 5;
```
----
### `integral_constant` version
```c++
template <typename X, typename Y>
struct plus {
using type = integral_constant<
decltype(X::value + Y::value),
X::value + Y::value
>;
};
using three = plus<integral_constant<int, 1>,
integral_constant<int, 2>>::type;
```
----
### But what if?
```c++
template <typename V, V v, typename U, U u>
constexpr auto
operator+(integral_constant<V, v>, integral_constant<U, u>)
{ return integral_constant<decltype(v + u), v + u>{}; }
template <typename V, V v, typename U, U u>
constexpr auto
operator==(integral_constant<V, v>, integral_constant<U, u>)
{ return integral_constant<bool, v == u>{}; }
// ...
```
----
### Tadam!
```c++
static_assert(decltype(
integral_constant<int, 1>{} + integral_constant<int, 4>{}
==
integral_constant<int, 5>{}
)::value, "");
```
----
### (or simply)
```c++
static_assert(integral_constant<int, 1>{} + integral_constant<int, 4>{}
==
integral_constant<int, 5>{}
, "");
```
----
### Pass me the sugar, please
```c++
template <int i>
constexpr integral_constant<int, i> int_{};
static_assert(int_<1> + int_<4> == int_<5>, "");
```
----
### More sugar
```c++
template <char ...c>
constexpr auto operator"" _c() {
// parse the characters and return an integral_constant
}
static_assert(1_c + 4_c == 5_c, "");
```
====================
### Euclidean distance
$$
\mathrm{distance}\left((x_1, y_1), (x_2, y_2)\right)
:= \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}
$$
----
### Compile-time arithmetic: then
%%arithmetic-then%%
----
### Compile-time arithmetic: now
%%arithmetic-now%%
----
### But runtime arithmetic works too
%%arithmetic-now-dynamic%%
====================
### Pretty cool? Wait!
```c++
template <typename T, T n>
struct integral_constant {
// ...
template <typename F>
void times(F f) const {
f(); f(); ... f(); // n times
}
};
```
----
### Loop unrolling: then
%%unrolling-then%%
----
### Loop unrolling: now
%%unrolling-now%%
----
### Sceptical?
```
_main:
; snip
push rbp
mov rbp, rsp
call __Z1fv
call __Z1fv
call __Z1fv
call __Z1fv
call __Z1fv
call __Z1fv
call __Z1fv
call __Z1fv
call __Z1fv
call __Z1fv
xor eax, eax
pop rbp
ret
```
====================
### So far so good
----
### What if?
```c++
template <typename ...T>
struct tuple {
// ...
template <typename N>
constexpr decltype(auto) operator[](N const&) {
return std::get<N::value>(*this);
}
};
```
----
### Accessing an element of a tuple: then
```c++
tuple<int, char, float> values = {1, 'x', 3.4f};
char x = std::get<1>(values);
```
----
### Accessing an element of a tuple: now
```c++
tuple<int, char, float> values = {1, 'x', 3.4f};
char x = values[1_c];
```
====================
### Why stop here?
- `std::ratio`
- `std::integer_sequence`
==============================================================================
### What are types?
Note:
This section introduces the type/value unification.
----
### Aren't they values after all?
```cpp
using result = add_pointer<int>::type;
```
----
### Let's treat them as such!
```cpp
class Type {
// ...
};
Type t{...};
```
====================
### What are metafunctions?
----
### Aren't they functions after all?
```c++
template <typename T>
struct add_pointer {
using type = T*;
};
```
----
### Let's treat them as such!
```c++
Type add_pointer(Type);
bool is_pointer(Type);
bool operator==(Type t, Type u);
// ...
Type t{...};
Type p = add_pointer(t);
assert(is_pointer(p));
```
====================
### Cool idea, but useless for metaprogramming
====================
### Easy fix: use templates
%%type_unification-Type%%
Note:
Make explicit the link between this and what we did in the previous section
with integral constants.
----
### Easy fix: use templates
%%type_unification-metafunction%%
----
### Tadam!
%%type_unification-usage%%
----
### Sugar
%%type_unification-sugar%%
====================
## But what does that buy us?
====================
### Types are now first class citizens!
%%type_unification-first_class%%
====================
### Full language can be used
__Before__
%%full_language-then%%
----
__After__
%%full_language-now%%
====================
### Only one library is required
__Before__
%%onelib-then%%
----
__After__
%%onelib-now%%
====================
### Unified syntax means more reuse
#### (Amphibious EDSL using Boost.Proto)
%%proto%%
====================
### Unified syntax means more consistency
__Before__
%%map-then%%
----
__After__
%%map-now%%
====================
### So we can represent types as values
----
### But how can we get back the types?
```c++
auto t = add_pointer(type<int>); // could be a complex type computation
using T = the-type-represented-by-t;
// do something useful with T here...
```
----
### Easy fix: use nested alias
```c++
template <typename T>
struct Type {
using type = T;
};
```
----
### And then `decltype`
```c++
auto t = add_pointer(type<int>);
using T = decltype(t)::type;
static_assert(std::is_same<T, int*>{}, "");
// do something useful with T here...
```
====================
### 3 step process
1. Wrap types into `type<...>`
2. Perform computations
3. Unwrap with `decltype(...)::type`
----
## Isn't that cumbersome?
### Not really <!-- .element class="fragment" -->
----
### Only done at some thin boundaries
```c++
auto t = type<T>;
auto result = huge_type_computation(t);
using Result = decltype(result)::type;
```
----
### Not always required
```c++
auto t = type<T>;
auto result = type_computation(t);
static_assert(result == type<Something>, "");
```
Note:
We did not have to do the third step because we did not need the type itself.
----
### Even then, it's not that bad
----
### Finding smallest type: then
%%smallest_type-then%%
----
### Finding smallest type: now
%%smallest_type-now%%
Note:
Also note that this is a very good example of a short type-only computation,
which is where we would expect the new paradigm to suffer the most.
====================
### So types are objects
### What should be their interface? <!-- .element class="fragment" -->
----
### It's precisely `<type_traits>`!
```c++
add_pointer -> std::add_pointer
add_const -> std::add_const
add_volatile -> std::add_volatile
// ...
is_pointer -> std::is_pointer
is_const -> std::is_const
is_volatile -> std::is_volatile
// ...
operator== -> std::is_same
// ...
```
----
### There's a generic lifting process
----
### Let's reconsider:
```c++
template <typename T>
Type<T*> add_pointer(Type<T>) { return {}; }
```
----
### This could also be written as
```c++
template <typename T>
auto add_pointer(Type<T>) {
return type<typename std::add_pointer<T>::type>;
}
```
----
### There's a pattern
```c++
template <template <typename ...> class F>
struct Metafunction {
template <typename ...T>
auto operator()(Type<T> ...) const {
return type<
typename F<T...>::type
>;
}
};
Metafunction<std::add_pointer> add_pointer{};
auto i = type<int>;
auto i_ptr = add_pointer(i);
static_assert(is_pointer(i_ptr), "");
```
----
### Sugar, again
```c++
template <template <typename ...> class F>
constexpr Metafunction<F> metafunction{};
auto add_pointer = metafunction<std::add_pointer>;
auto remove_reference = metafunction<std::remove_reference>;
auto add_const = metafunction<std::add_const>;
// ...
```
====================
### Case study: switch for `boost::any`
%%switch_any-now-usage%%
----
### Disclaimer:
#### Not as good as Sebastian's
----
### First
%%switch_any-now-impl1%%
----
### The beast
%%switch_any-now-impl2%%
----
### Processing cases
%%switch_any-now-impl3%%
----
### Base case
%%switch_any-now-impl4%%
----