Imported Upstream version 1.64.0
[platform/upstream/boost.git] / libs / hana / doc / tutorial.hpp
1 // Copyright Louis Dionne 2013-2017
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
4
5 /*!
6
7 @mainpage User Manual
8
9 @tableofcontents
10
11
12
13
14
15
16
17
18
19
20 @section tutorial-description Description
21
22 ------------------------------------------------------------------------------
23 Hana is a header-only library for C++ metaprogramming suited for computations
24 on both types and values. The functionality it provides is a superset of what
25 is provided by the well established [Boost.MPL][] and [Boost.Fusion][]
26 libraries. By leveraging C++11/14 implementation techniques and idioms,
27 Hana boasts faster compilation times and runtime performance on par or better
28 than previous metaprogramming libraries, while noticeably increasing the level
29 of expressiveness in the process. Hana is easy to extend in a ad-hoc manner
30 and it provides out-of-the-box inter-operation with Boost.Fusion, Boost.MPL
31 and the standard library.
32
33
34
35
36
37
38
39
40
41
42 @section tutorial-installation Prerequisites and installation
43
44 ------------------------------------------------------------------------------
45 Hana is a header-only library without external dependencies (not even the rest
46 of Boost). Hence, using Hana in your own project is very easy. Basically, just
47 download the project and add the `include/` directory to your compiler's header
48 search path and you are done. However, if you want to cleanly install Hana, you
49 have a couple of options:
50
51 1. __Install Boost__\n
52 Hana is included in the [Boost][] distribution starting from Boost 1.61.0, so
53 installing that will give you access to Hana.
54
55 2. __Install locally for CMake projects__\n
56 If you use CMake in a project, you can use the provided [FindHana.cmake][Hana.findmodule]
57 module to setup Hana as an external CMake project. The module allows using an
58 already-installed version of Hana, or installing Hana locally to your CMake
59 project, without needing a system-wide installation.
60
61 3. __Use Homebrew__\n
62 On Mac OS, Hana can be installed with [Homebrew][]:
63 @code{.sh}
64 brew install hana
65 @endcode
66
67 4. __Install manually__\n
68 You can download the code from the official GitHub [repository][Hana.repository]
69 and install the library manually by issuing the following commands from the root
70 of the project (requires [CMake][]):
71 @code{.sh}
72 mkdir build && cd build
73 cmake ..
74 cmake --build . --target install
75 @endcode
76 This will install Hana to the default install-directory for your platform
77 (`/usr/local` for Unix, `C:/Program Files` for Windows). If you want to
78 install Hana in a custom location, you can use
79 @code{.sh}
80 cmake .. -DCMAKE_INSTALL_PREFIX=/custom/install/prefix
81 @endcode
82
83 @note
84 - Both the manual installation and the Homebrew installation will also install
85 a `hana.pc` file for use with [pkg-config][].
86
87 - Do not mix a system-wide installation of Hana with a system-wide installation
88 of Boost, because both installations will clash. You won't know which version of
89 Hana is being used, and that could break libraries that depend on the version of
90 Hana provided with Boost (or vice-versa). Generally speaking, you should favor
91 local installations whenever possible.
92
93 Finally, if you want to contribute to Hana, you can see how to best setup your
94 environment for development in the [README][Hana.hacking].
95
96 @subsection tutorial-installation-requirements Compiler requirements
97
98 The library relies on a C++14 compiler and standard library, but nothing else
99 is required. Here is a table of the current C++14 compilers/toolchains with
100 comments regarding support for Hana:
101
102 Compiler/Toolchain | Status
103 ------------------ | ------
104 Clang >= 3.5.0     | Fully working; tested on each push to GitHub
105 Xcode >= 6.3       | Fully working; tested on each push to GitHub
106 GCC >= 6.0.0       | Fully working; tested on each push to GitHub
107
108 More specifically, Hana requires a compiler/standard library supporting the
109 following C++14 features (non-exhaustively):
110 - Generic lambdas
111 - Generalized `constexpr`
112 - Variable templates
113 - Automatically deduced return type
114 - All the C++14 type traits from the `<type_traits>` header
115
116 More information for specific platforms is available on [the wiki][Hana.wiki].
117
118
119
120
121
122
123
124
125
126
127 @section tutorial-support Support
128
129 ------------------------------------------------------------------------------
130
131 If you have a problem, please review the [FAQ](@ref tutorial-rationales) and
132 [the wiki][Hana.wiki]. Searching [the issues][Hana.issues] for your problem is
133 also a good idea. If that doesn't help, feel free to chat with us in [Gitter][Hana.chat],
134 or open a new issue. [StackOverflow][] with the [boost-hana][Hana.StackOverflow]
135 tag is the preferred place to ask questions on usage. If you are encountering
136 what you think is a bug, please open an issue.
137
138
139
140
141
142
143
144
145
146
147 @section tutorial-introduction Introduction
148
149 ------------------------------------------------------------------------------
150 When Boost.MPL first appeared, it provided C++ programmers with a huge relief
151 by abstracting tons of template hackery behind a workable interface. This
152 breakthrough greatly contributed to making C++ template metaprogramming more
153 mainstream, and today the discipline is deeply rooted in many serious projects.
154 Recently, C++11 and C++14 brought many major changes to the language, some of
155 which make metaprogramming much easier, while others drastically widen the
156 design space for libraries. A natural question then arises: is it still
157 desirable to have abstractions for metaprogramming, and if so, which ones?
158 After investigating different options like the [MPL11][], the answer eventually
159 came by itself in the form of a library; Hana. The key insight to Hana is that
160 the manipulation of types and values are nothing but two sides of the same
161 coin. By unifying both concepts, metaprogramming becomes easier and new
162 exciting possibilities open before us.
163
164
165 @subsection tutorial-introduction-quadrants C++ computational quadrants
166
167 But to really understand what is Hana all about, it is essential to understand
168 the different types of computations in C++. We will focus our attention on
169 four different kinds of computations, even though a finer grained separation
170 would be possible. First, we have runtime computations, which are the usual
171 computations we use in C++. In that world, we have runtime containers,
172 runtime functions and runtime algorithms:
173
174 @snippet example/tutorial/introduction.cpp runtime
175
176 The usual toolbox for programming within this quadrant is the C++ standard
177 library, which provides reusable algorithms and containers operating at
178 runtime. Since C++11, a second kind of computation is possible: `constexpr`
179 computations. There, we have `constexpr` containers, `constexpr` functions
180 and `constexpr` algorithms:
181
182 @code{cpp}
183 constexpr int factorial(int n) {
184   return n == 0 ? 1 : n * factorial(n - 1);
185 }
186
187 template <typename T, std::size_t N, typename F>
188   constexpr std::array<std::result_of_t<F(T)>, N>
189 transform(std::array<T, N> array, F f) {
190   // ...
191 }
192
193 constexpr std::array<int, 4> ints{{1, 2, 3, 4}};
194 constexpr std::array<int, 4> facts = transform(ints, factorial);
195 static_assert(facts == std::array<int, 4>{{1, 2, 6, 24}}, "");
196 @endcode
197
198 @note
199 For the above code to actually work, `std::array`'s `operator==` would have to
200 be marked `constexpr`, which is not the case (even in C++14).
201
202 Basically, a `constexpr` computation is different from a runtime computation
203 in that it is simple enough to be evaluated (interpreted, really) by the
204 compiler. In general, any function that does not perform anything too
205 _unfriendly_ to the compiler's evaluator (like throwing or allocating memory)
206 can be marked `constexpr` without any further change. This makes `constexpr`
207 computations very similar to runtime computations, except `constexpr`
208 computations are more restricted and they gain the ability to be evaluated
209 at compile-time. Unfortunately, there is no commonly used toolbox for
210 `constexpr`-programming, i.e. there is no widely adopted "standard library"
211 for `constexpr` programming. However, the [Sprout][] library may be worth
212 checking out for those with some interest in `constexpr` computations.
213
214 The third kind of computations are heterogeneous computations. Heterogeneous
215 computations differ from normal computations in that instead of having
216 containers holding homogeneous objects (all objects having the same type),
217 the containers may hold objects with different types. Furthermore, functions
218 in this quadrant of computation are _heterogeneous_ functions, which is a
219 complicated way of talking about template functions. Similarly, we have
220 heterogeneous algorithms that manipulate heterogeneous containers and
221 functions:
222
223 @snippet example/tutorial/introduction.cpp heterogeneous
224
225 If manipulating heterogeneous containers seems overly weird to you, just think
226 of it as glorified `std::tuple` manipulation. In a C++03 world, the go-to
227 library for doing this kind of computation is [Boost.Fusion][], which provides
228 several data structures and algorithms to manipulate heterogeneous collections
229 of data. The fourth and last quadrant of computation that we'll be considering
230 here is the quadrant of type-level computations. In this quadrant, we have
231 type-level containers, type-level functions (usually called metafunctions)
232 and type-level algorithms. Here, everything operates on types: containers hold
233 types and metafunctions take types as arguments and return types as results.
234
235 @snippet example/tutorial/introduction.cpp type-level
236
237 The realm of type-level computations has been explored quite extensively, and
238 the de-facto solution for type-level computations in C++03 is a library named
239 [Boost.MPL][], which provides type-level containers and algorithms. For
240 low-level type transformations, the metafunctions provided by the
241 `<type_traits>` standard header can also be used since C++11.
242
243
244 @subsection tutorial-quadrants-about What is this library about?
245
246 So all is good, but what is this library actually about? Now that we have set
247 the table by clarifying the kinds of computations available to us in C++, the
248 answer might strike you as very simple. __The purpose of Hana is to merge the
249 3rd and the 4th quadrants of computation__. More specifically, Hana is a
250 (long-winded) constructive proof that heterogeneous computations are strictly
251 more powerful than type-level computations, and that we can therefore express
252 any type-level computation by an equivalent heterogeneous computation. This
253 construction is done in two steps. First, Hana is a fully featured library of
254 heterogeneous algorithms and containers, a bit like a modernized Boost.Fusion.
255 Secondly, Hana provides a way of translating any type-level computation into its
256 equivalent heterogeneous computation and back, which allows the full machinery
257 of heterogeneous computations to be reused for type-level computations without
258 any code duplication. Of course, the biggest advantage of this unification is
259 seen by the user, as you will witness by yourself.
260
261
262
263
264
265
266
267
268
269
270 @section tutorial-quickstart Quick start
271
272 ------------------------------------------------------------------------------
273 The goal of this section is to introduce the main concepts of the library
274 from a very high level and at a fairly rapid pace; don't worry if you don't
275 understand everything that's about to be thrown at you. However, this tutorial
276 assumes the reader is already at least _familiar_ with basic metaprogramming
277 and the [C++14 standard][C++14]. First, let's include the library:
278
279 @snippet example/tutorial/quickstart.cpp includes
280
281 Unless specified otherwise, the documentation assumes the above lines to be
282 present before examples and code snippets. Also note that finer grained
283 headers are provided and will be explained in the [Header organization]
284 (@ref tutorial-header_organization) section. For the purpose of the
285 quickstart, let's now include some additional headers and define some
286 lovely animal types that we'll need below:
287
288 @snippet example/tutorial/quickstart.cpp additional_setup
289
290 If you are reading this documentation, chances are you already know
291 `std::tuple` and `std::make_tuple`. Hana provides its own tuple and
292 `make_tuple`:
293
294 @snippet example/tutorial/quickstart.cpp animals
295
296 This creates a tuple, which is like an array, except that it can hold elements
297 with different types. Containers that can hold elements with different types
298 such as this are called heterogeneous containers. While the standard library
299 provides very few operations to manipulate `std::tuple`s, Hana provides several
300 operations and algorithms to manipulate its own tuples:
301
302 @snippet example/tutorial/quickstart.cpp algorithms
303
304 @note
305 `1_c` is a [C++14 user-defined literal][C++14.udl] creating a
306 [compile-time number](@ref tutorial-integral). These user-defined
307 literals are contained in the `boost::hana::literals` namespace,
308 hence the `using` directive.
309
310 Notice how we pass a [C++14 generic lambda][C++14.glambda] to `transform`;
311 this is required because the lambda will first be called with a `Fish`, then
312 a `Cat`, and finally a `Dog`, which all have different types. Hana provides
313 most of the algorithms provided by the C++ standard library, except they work
314 on tuples and related heterogeneous containers instead of `std::vector` &
315 friends. In addition to working with heterogeneous values, Hana makes it
316 possible to perform type-level computations with a natural syntax, all at
317 compile-time and with no overhead whatsoever. This compiles and does just
318 what you would expect:
319
320 @snippet example/tutorial/quickstart.cpp type-level
321
322 @note
323 `type_c<...>` is not a type! It is a [C++14 variable template][C++14.vtemplate]
324 yielding an object representing a type for Hana. This is explained in the
325 section on [type computations](@ref tutorial-type).
326
327 In addition to heterogeneous and compile-time sequences, Hana provides several
328 features to make your metaprogramming nightmares a thing of the past. For
329 example, one can check for the existence of a struct member with one easy
330 line instead of relying on [clunky SFINAE hacks][SO.sfinae]:
331
332 @snippet example/tutorial/quickstart.cpp has_name
333
334 Writing a serialization library? Stop crying, we've got you covered.
335 Reflection can be added to user-defined types very easily. This allows
336 iterating over the members of a user-defined type, querying members with
337 a programmatic interface and much more, without any runtime overhead:
338
339 @snippet example/tutorial/quickstart.cpp serialization
340
341 That's cool, but I can already hear you complaining about incomprehensible
342 error messages. However, it turns out Hana was built for humans, not
343 professional template metaprogrammers, and this shows. Let's intentionally
344 screw up and see what kind of mess is thrown at us. First, the mistake:
345
346 @snippet example/tutorial/quickstart.cpp screw_up
347
348 Now, the punishment:
349
350 @code{cpp}
351 error: static_assert failed "hana::for_each(xs, f) requires 'xs' to be Foldable"
352         static_assert(Foldable<S>::value,
353         ^             ~~~~~~~~~~~~~~~~~~
354 note: in instantiation of function template specialization
355       'boost::hana::for_each_t::operator()<
356         std::__1::basic_ostream<char> &, (lambda at [snip])>' requested here
357   hana::for_each(os, [&](auto member) {
358   ^
359 note: in instantiation of function template specialization
360     'main()::(anonymous class)::operator()<Person>' requested here
361 serialize(std::cout, john);
362          ^
363 @endcode
364
365 Not that bad, right? However, since small examples are very good to show off
366 without actually doing something useful, let's examine a real world example.
367
368
369 @subsection tutorial-quickstart-any A real world example
370
371 In this section our goal will be to implement a kind of `switch` statement
372 able to process `boost::any`s. Given a `boost::any`, the goal is to dispatch
373 to the function associated to the dynamic type of the `any`:
374
375 @snippet example/tutorial/quickstart.switchAny.cpp usage
376
377 @note
378 In the documentation, we will often use the `s` suffix on string literals to
379 create `std::string`s without syntactic overhead. This is a standard-defined
380 [C++14 user-defined literal][C++14.udl].
381
382 Since the any holds a `char`, the second function is called with the `char`
383 inside it. If the `any` had held an `int` instead, the first function would
384 have been called with the `int` inside it. When the dynamic type of the `any`
385 does not match any of the covered cases, the `%default_` function is called
386 instead. Finally, the result of the `switch` is the result of calling the
387 function associated to the `any`'s dynamic type. The type of that result is
388 inferred to be the common type of the result of all the provided functions:
389
390 @snippet example/tutorial/quickstart.switchAny.cpp result_inference
391
392 We'll now look at how this utility can be implemented using Hana. The first
393 step is to associate each type to a function. To do so, we represent each
394 `case_` as a `hana::pair` whose first element is a type and whose second
395 element is a function. Furthermore, we (arbitrarily) decide to represent the
396 `%default_` case as a `hana::pair` mapping a dummy type to a function:
397
398 @snippet example/tutorial/quickstart.switchAny.cpp cases
399
400 To provide the interface we showed above, `switch_` will have to return a
401 function taking the cases. In other words, `switch_(a)` must be a function
402 taking any number of cases (which are `hana::pair`s), and performing the logic
403 to dispatch `a` to the right function. This can easily be achieved by having
404 `switch_` return a C++14 generic lambda:
405
406 @code{cpp}
407 template <typename Any>
408 auto switch_(Any& a) {
409   return [&a](auto ...cases_) {
410     // ...
411   };
412 }
413 @endcode
414
415 However, since parameter packs are not very flexible, we'll put the cases
416 into a tuple so we can manipulate them:
417
418 @code{cpp}
419 template <typename Any>
420 auto switch_(Any& a) {
421   return [&a](auto ...cases_) {
422     auto cases = hana::make_tuple(cases_...);
423     // ...
424   };
425 }
426 @endcode
427
428 Notice how the `auto` keyword is used when defining `cases`; it is often
429 easier to let the compiler deduce the type of the tuple and use `make_tuple`
430 instead of working out the types manually. The next step is to separate the
431 default case from the rest of the cases. This is where things start to get
432 interesting. To do so, we use Hana's `find_if` algorithm, which works a bit
433 like `std::find_if`:
434
435 @code{cpp}
436 template <typename Any>
437 auto switch_(Any& a) {
438   return [&a](auto ...cases_) {
439     auto cases = hana::make_tuple(cases_...);
440
441     auto default_ = hana::find_if(cases, [](auto const& c) {
442       return hana::first(c) == hana::type_c<default_t>;
443     });
444
445     // ...
446   };
447 }
448 @endcode
449
450 `find_if` takes a `tuple` and a predicate, and returns the first element of
451 the tuple which satisfies the predicate. The result is returned as a
452 `hana::optional`, which is very similar to a `std::optional`, except
453 whether that optional value is empty or not is known at compile-time. If the
454 predicate is not satisfied for any element of the `tuple`, `find_if` returns
455 `nothing` (an empty value). Otherwise, it returns `just(x)` (a non-empty value),
456 where `x` is the first element satisfying the predicate. Unlike predicates
457 used in STL algorithms, the predicate used here must be generic because the
458 tuple's elements are heterogeneous. Furthermore, that predicate must return
459 what Hana calls an `IntegralConstant`, which means that the predicate's result
460 must be known at compile-time. These details are explained in the section on
461 [cross-phase algorithms](@ref tutorial-algorithms-cross_phase). Inside the
462 predicate, we simply compare the type of the case's first element to
463 `type_c<default_t>`. If you recall that we were using `hana::pair`s to encode
464 cases, this simply means that we're finding the default case among all of the
465 provided cases. But what if no default case was provided? We should fail at
466 compile-time, of course!
467
468 @code{cpp}
469 template <typename Any>
470 auto switch_(Any& a) {
471   return [&a](auto ...cases_) {
472     auto cases = hana::make_tuple(cases_...);
473
474     auto default_ = hana::find_if(cases, [](auto const& c) {
475       return hana::first(c) == hana::type_c<default_t>;
476     });
477     static_assert(default_ != hana::nothing,
478       "switch is missing a default_ case");
479
480     // ...
481   };
482 }
483 @endcode
484
485 Notice how we can use `static_assert` on the result of the comparison with
486 `nothing`, even though `%default_` is a non-`constexpr` object? Boldly, Hana
487 makes sure that no information that's known at compile-time is lost to the
488 runtime, which is clearly the case of the presence of a `%default_` case.
489 The next step is to gather the set of non-default cases. To achieve this, we
490 use the `filter` algorithm, which keeps only the elements of the sequence
491 satisfying the predicate:
492
493 @code{cpp}
494 template <typename Any>
495 auto switch_(Any& a) {
496   return [&a](auto ...cases_) {
497     auto cases = hana::make_tuple(cases_...);
498
499     auto default_ = hana::find_if(cases, [](auto const& c) {
500       return hana::first(c) == hana::type_c<default_t>;
501     });
502     static_assert(default_ != hana::nothing,
503       "switch is missing a default_ case");
504
505     auto rest = hana::filter(cases, [](auto const& c) {
506       return hana::first(c) != hana::type_c<default_t>;
507     });
508
509     // ...
510   };
511 }
512 @endcode
513
514 The next step is to find the first case matching the dynamic type of the `any`,
515 and then call the function associated to that case. The simplest way to do this
516 is to use classic recursion with variadic parameter packs. Of course, we could
517 probably intertwine Hana algorithms in a convoluted way to achieve this, but
518 sometimes the best way to do something is to write it from scratch using basic
519 techniques. To do so, we'll call an implementation function with the contents
520 of the `rest` tuple by using the `unpack` function:
521
522 @snippet example/tutorial/quickstart.switchAny.cpp switch_
523
524 `unpack` takes a `tuple` and a function, and calls the function with the content
525 of the `tuple` as arguments. The result of `unpack` is the result of calling that
526 function. In our case, the function is a generic lambda which in turn calls the
527 `process` function. Our reason for using `unpack` here was to turn the `rest`
528 tuple into a parameter pack of arguments, which are easier to process recursively
529 than tuples. Before we move on to the `process` function, it is worthwhile to
530 explain what `second(*%default_)` is all about. As we explained earlier,
531 `%default_` is an optional value. Like `std::optional`, this optional value
532 overloads the dereference operator (and the arrow operator) to allow accessing
533 the value inside the `optional`. If the optional is empty (`nothing`), a
534 compile-time error is triggered. Since we know `%default_` is not empty (we
535 checked that just above), what we're doing is simply pass the function
536 associated to the default case to the `process` function. We're now ready
537 for the final step, which is the implementation of the `process` function:
538
539 @snippet example/tutorial/quickstart.switchAny.cpp process
540
541 There are two overloads of this function: an overload for when there is at least
542 one case to process, and the base case overload for when there's only the default
543 case. As we would expect, the base case simply calls the default function and
544 returns that result. The other overload is slightly more interesting. First,
545 we retrieve the type associated to that case and store it in `T`. This
546 `decltype(...)::%type` dance might seem convoluted, but it is actually quite
547 simple. Roughly speaking, this takes a type represented as an object (a `type<T>`)
548 and pulls it back down to the type level (a `T`). The details are explained in
549 the section on [type-level computations](@ref tutorial-type). Then, we compare
550 whether the dynamic type of the `any` matches this case, and if so we call the
551 function associated to this case with the `any` casted to the proper type.
552 Otherwise, we simply call `process` recursively with the rest of the cases.
553 Pretty simple, wasn't it? Here's the final solution:
554
555 @snippet example/tutorial/quickstart.switchAny.cpp full
556
557 That's it for the quick start! This example only introduced a couple of useful
558 algorithms (`find_if`, `filter`, `unpack`) and heterogeneous containers
559 (`tuple`, `optional`), but rest assured that there is much more. The next
560 sections of the tutorial gradually introduce general concepts pertaining to
561 Hana in a friendly way, but you may use the following cheatsheet for quick
562 reference if you want to start coding right away. This cheatsheet contains
563 the most frequently used algorithms and containers, along with a short
564 description of what each of them does.
565
566
567 @section tutorial-cheatsheet Cheatsheet
568
569 ### Remarks
570 - Most algorithms work on both types and values (see the section on
571   [type computations](@ref tutorial-type))
572 - Algorithms always return their result as a new container; no in-place
573   mutation is ever performed (see the section on [algorithms]
574   (@ref tutorial-algorithms))
575 - All algorithms are `constexpr` function objects
576
577
578 container          | description
579 :----------------- | :----------
580 <code>[tuple](@ref boost::hana::tuple)</code>                         | General purpose index-based heterogeneous sequence with a fixed length. Use this as a `std::vector` for heterogeneous objects.
581 <code>[optional](@ref boost::hana::optional)</code>                   | Represents an optional value, i.e. a value that can be empty. This is a bit like `std::optional`, except that the emptiness is known at compile-time.
582 <code>[map](@ref boost::hana::map)</code>                             | Unordered associative array mapping (unique) compile-time entities to arbitrary objects. This is like `std::unordered_map` for heterogeneous objects.
583 <code>[set](@ref boost::hana::set)</code>                             | Unordered container holding unique keys that must be compile-time entities. This is like `std::unordered_set` for heterogeneous objects.
584 <code>[range](@ref boost::hana::range)</code>                         | Represents an interval of compile-time numbers. This is like `std::integer_sequence`, but better.
585 <code>[pair](@ref boost::hana::pair)</code>                           | Container holding two heterogeneous objects. Like `std::pair`, but compresses the storage of empty types.
586 <code>[string](@ref boost::hana::string)</code>                       | Compile-time string.
587 <code>[type](@ref boost::hana::type)</code>                           | Container representing a C++ type. This is the root of the unification between types and values, and is of interest for MPL-style computations (type-level computations).
588 <code>[integral_constant](@ref boost::hana::integral_constant)</code> | Represents a compile-time number. This is very similar to `std::integral_constant`, except that `hana::integral_constant` also defines operators and more syntactic sugar.
589 <code>[lazy](@ref boost::hana::lazy)</code>                           | Encapsulates a lazy value or computation.
590 <code>[basic_tuple](@ref boost::hana::basic_tuple)</code>             | Stripped-down version of `hana::tuple`. Not standards conforming, but more compile-time efficient.
591
592
593 function                                                                                  | description
594 :------------------------------------------                                               | :----------
595 <code>[adjust](@ref ::boost::hana::adjust)(sequence, value, f)</code>                     | Apply a function to each element of a sequence that compares equal to some value and return the result.
596 <code>[adjust_if](@ref ::boost::hana::adjust_if)(sequence, predicate, f)</code>           | Apply a function to each element of a sequence satisfying some predicate and return the result.
597 <code>{[all](@ref ::boost::hana::all),[any](@ref ::boost::hana::any),[none](@ref ::boost::hana::none)}(sequence)</code> | Returns whether all/any/none of the elements of a sequence are true-valued.
598 <code>{[all](@ref ::boost::hana::all_of),[any](@ref ::boost::hana::any_of),[none](@ref ::boost::hana::none_of)}_of(sequence, predicate)</code> | Returns whether all/any/none of the elements of the sequence satisfy some predicate.
599 <code>[append](@ref ::boost::hana::append)(sequence, value)</code>                        | Append an element to a sequence.
600 <code>[at](@ref ::boost::hana::at)(sequence, index)</code>                                | Returns the n-th element of a sequence. The index must be an `IntegralConstant`.
601 <code>[back](@ref ::boost::hana::back)(sequence)</code>                                   | Returns the last element of a non-empty sequence.
602 <code>[concat](@ref ::boost::hana::concat)(sequence1, sequence2)</code>                   | Concatenate two sequences.
603 <code>[contains](@ref ::boost::hana::contains)(sequence, value)</code>                    | Returns whether a sequence contains the given object.
604 <code>[count](@ref ::boost::hana::count)(sequence, value)</code>                          | Returns the number of elements that compare equal to the given value.
605 <code>[count_if](@ref ::boost::hana::count_if)(sequence, predicate)</code>                | Returns the number of elements that satisfy the predicate.
606 <code>[drop_front](@ref ::boost::hana::drop_front)(sequence[, n])</code>                  | Drop the first `n` elements from a sequence, or the whole sequence if `length(sequence) <= n`. `n` must be an `IntegralConstant`. When not provided, `n` defaults to 1.
607 <code>[drop_front_exactly](@ref ::boost::hana::drop_front_exactly)(sequence[, n])</code>  | Drop the first `n` elements from a sequence. `n` must be an `IntegralConstant` and the sequence must have at least `n` elements. When not provided, `n` defaults to 1.
608 <code>[drop_back](@ref ::boost::hana::drop_back)(sequence[, n])</code>                    | Drop the last `n` elements from a sequence, or the whole sequence if `length(sequence) <= n`. `n` must be an `IntegralConstant`. When not provided, `n` defaults to 1.
609 <code>[drop_while](@ref ::boost::hana::drop_while)(sequence, predicate)</code>            | Drops elements from a sequence while a predicate is satisfied. The predicate must return an `IntegralConstant`.
610 <code>[fill](@ref ::boost::hana::fill)(sequence, value)</code>                            | Replace all the elements of a sequence with some value.
611 <code>[filter](@ref ::boost::hana::filter)(sequence, predicate)</code>                    | Remove all the elements that do not satisfy a predicate. The predicate must return an `IntegralConstant`.
612 <code>[find](@ref ::boost::hana::find)(sequence, value)</code>                            | Find the first element of a sequence which compares equal to some value and return `just` it, or return `nothing`. See `hana::optional`.
613 <code>[find_if](@ref ::boost::hana::find_if)(sequence, predicate)</code>                  | Find the first element of a sequence satisfying the predicate and return `just` it, or return `nothing`. See `hana::optional`.
614 <code>[flatten](@ref ::boost::hana::flatten)(sequence)</code>                             | Flatten a sequence of sequences, a bit like `std::tuple_cat`.
615 <code>[fold_left](@ref ::boost::hana::fold_left)(sequence[, state], f)</code>             | Accumulates the elements of a sequence from the left, optionally with a provided initial state.
616 <code>[fold_right](@ref ::boost::hana::fold_right)(sequence[, state], f)</code>           | Accumulates the elements of a sequence from the right, optionally with a provided initial state.
617 <code>[fold](@ref ::boost::hana::fold)(sequence[, state], f)</code>                       | Equivalent to `fold_left`; provided for consistency with Boost.MPL and Boost.Fusion.
618 <code>[for_each](@ref ::boost::hana::for_each)(sequence, f)</code>                        | Call a function on each element of a sequence. Returns `void`.
619 <code>[front](@ref ::boost::hana::front)(sequence)</code>                                 | Returns the first element of a non-empty sequence.
620 <code>[group](@ref ::boost::hana::group)(sequence[, predicate])</code>                    | %Group adjacent elements of a sequence which all satisfy (or all do not satisfy) some predicate. The predicate defaults to equality, in which case the elements must be `Comparable`.
621 <code>[insert](@ref ::boost::hana::insert)(sequence, index, element)</code>               | Insert an element at a given index. The index must be an `IntegralConstant`.
622 <code>[insert_range](@ref ::boost::hana::insert_range)(sequence, index, elements)</code>  | Insert a sequence of elements at a given index. The index must be an `IntegralConstant`.
623 <code>[is_empty](@ref ::boost::hana::is_empty)(sequence)</code>                           | Returns whether a sequence is empty as an `IntegralConstant`.
624 <code>[length](@ref ::boost::hana::length)(sequence)</code>                               | Returns the length of a sequence as an `IntegralConstant`.
625 <code>[lexicographical_compare](@ref ::boost::hana::lexicographical_compare)(sequence1, sequence2[, predicate])</code> | Performs a lexicographical comparison of two sequences, optionally with a custom predicate, by default with `hana::less`.
626 <code>[maximum](@ref ::boost::hana::maximum)(sequence[, predicate])</code>                | Returns the greatest element of a sequence, optionally according to a predicate. The elements must be `Orderable` if no predicate is provided.
627 <code>[minimum](@ref ::boost::hana::minimum)(sequence[, predicate])</code>                | Returns the smallest element of a sequence, optionally according to a predicate. The elements must be `Orderable` if no predicate is provided.
628 <code>[partition](@ref ::boost::hana::partition)(sequence, predicate)</code>              | Partition a sequence into a pair of elements that satisfy some predicate, and elements that do not satisfy it.
629 <code>[prepend](@ref ::boost::hana::prepend)(sequence, value)</code>                      | Prepend an element to a sequence.
630 <code>[remove](@ref ::boost::hana::remove)(sequence, value)</code>                        | Remove all the elements that are equal to a given value.
631 <code>[remove_at](@ref ::boost::hana::remove_at)(sequence, index)</code>                  | Remove the element at the given index. The index must be an `IntegralConstant`.
632 <code>[remove_if](@ref ::boost::hana::remove_if)(sequence, predicate)</code>              | Remove all the elements that satisfy a predicate. The predicate must return an `IntegralConstant`.
633 <code>[remove_range](@ref ::boost::hana::remove_range)(sequence, from, to)</code>         | Remove the elements at indices in the given `[from, to)` half-open interval. The indices must be `IntegralConstant`s.
634 <code>[replace](@ref ::boost::hana::replace)(sequence, oldval, newval)</code>             | Replace the elements of a sequence that compare equal to some value by some other value.
635 <code>[replace_if](@ref ::boost::hana::replace_if)(sequence, predicate, newval)</code>    | Replace the elements of a sequence that satisfy some predicate by some value.
636 <code>[reverse](@ref ::boost::hana::reverse)(sequence)</code>                             | Reverse the order of the elements in a sequence.
637 <code>[reverse_fold](@ref ::boost::hana::reverse_fold)(sequence[, state], f)</code>       | Equivalent to `fold_right`; provided for consistency with Boost.MPL and Boost.Fusion.
638 <code>[size](@ref ::boost::hana::size)(sequence)</code>                                   | Equivalent to `length`; provided for consistency with the C++ standard library.
639 <code>[slice](@ref ::boost::hana::slice)(sequence, indices)</code>                        | Returns a new sequence containing the elements at the given indices of the original sequence.
640 <code>[slice_c](@ref ::boost::hana::slice_c)<from, to>(sequence)</code>                   | Returns a new sequence containing the elements at indices contained in `[from, to)` of the original sequence.
641 <code>[sort](@ref ::boost::hana::sort)(sequence[, predicate])</code>                      | Sort (stably) the elements of a sequence, optionally according to a predicate. The elements must be `Orderable` if no predicate is provided.
642 <code>[take_back](@ref ::boost::hana::take_back)(sequence, number)</code>                 | Take the last n elements of a sequence, or the whole sequence if `length(sequence) <= n`. n must be an `IntegralConstant`.
643 <code>[take_front](@ref ::boost::hana::take_front)(sequence, number)</code>               | Take the first n elements of a sequence, or the whole sequence if `length(sequence) <= n`. n must be an `IntegralConstant`.
644 <code>[take_while](@ref ::boost::hana::take_while)(sequence, predicate)</code>            | Take elements of a sequence while some predicate is satisfied, and return that.
645 <code>[transform](@ref ::boost::hana::transform)(sequence, f)</code>                      | Apply a function to each element of a sequence and return the result.
646 <code>[unique](@ref ::boost::hana::unique)(sequence[, predicate])</code>                  | Removes all consecutive duplicates from a sequence. The predicate defaults to equality, in which case the elements must be `Comparable`.
647 <code>[unpack](@ref ::boost::hana::unpack)(sequence, f)</code>                            | Calls a function with the contents of a sequence. Equivalent to `f(x1, ..., xN)`.
648 <code>[zip](@ref ::boost::hana::zip)(s1, ..., sN)</code>                                  | Zip `N` sequences into a sequence of tuples. All the sequences must have the same length.
649 <code>[zip_shortest](@ref ::boost::hana::zip_shortest)(s1, ..., sN)</code>                | Zip `N` sequences into a sequence of tuples. The resulting sequence has the length of the shortest input sequence.
650 <code>[zip_with](@ref ::boost::hana::zip_with)(f, s1, ..., sN)</code>                     | Zip `N` sequences with a `N`-ary function. All the sequences must have the same length.
651 <code>[zip_shortest_with](@ref ::boost::hana::zip_shortest_with)(f, s1, ..., sN)</code>   | Zip `N` sequences with a `N`-ary function. The resulting sequence has the length of the shortest input sequence.
652
653
654
655
656
657
658
659
660
661
662 @section tutorial-assert Assertions
663
664 ------------------------------------------------------------------------------
665 In the rest of this tutorial, you will come across code snippets where different
666 kinds of assertions like `BOOST_HANA_RUNTIME_CHECK` and `BOOST_HANA_CONSTANT_CHECK`
667 are used. Like any sensible `assert` macro, they basically check that the
668 condition they are given is satisfied. However, in the context of heterogeneous
669 programming, some informations are known at compile-time, while others are known
670 only at runtime. The exact type of assertion that's used in a context tells you
671 whether the condition that's asserted upon can be known at compile-time or if it
672 must be computed at runtime, which is a very precious piece of information. Here
673 are the different kinds of assertions used in the tutorial, with a small
674 description of their particularities. For more details, you should check
675 the [reference on assertions](@ref group-assertions).
676
677 assertion                    | description
678 :--------------------------- | :----------
679 `BOOST_HANA_RUNTIME_CHECK`   | Assertion on a condition that is not known until runtime. This assertion provides the weakest form of guarantee.
680 `BOOST_HANA_CONSTEXPR_CHECK` | Assertion on a condition that would be `constexpr` if lambdas were allowed inside constant expressions. In other words, the only reason for it not being a `static_assert` is the language limitation that lambdas can't appear in constant expressions, which [might be lifted][N4487] in C++17.
681 `static_assert`              | Assertion on a `constexpr` condition. This is stronger than `BOOST_HANA_CONSTEXPR_CHECK` in that it requires the condition to be a constant expression, and it hence assures that the algorithms used in the expression are `constexpr`-friendly.
682 `BOOST_HANA_CONSTANT_CHECK`  | Assertion on a boolean `IntegralConstant`. This assertion provides the strongest form of guarantee, because an `IntegralConstant` can be converted to a `constexpr` value even if it is not `constexpr` itself.
683
684
685
686
687
688
689
690
691
692
693 @section tutorial-integral Compile-time numbers
694
695 ------------------------------------------------------------------------------
696 This section introduces the important notion of `IntegralConstant` and the
697 philosophy behind Hana's metaprogramming paradigm. Let's start with a rather
698 odd question. What is an `integral_constant`?
699
700 @code{cpp}
701 template<class T, T v>
702 struct integral_constant {
703   static constexpr T value = v;
704   typedef T value_type;
705   typedef integral_constant type;
706   constexpr operator value_type() const noexcept { return value; }
707   constexpr value_type operator()() const noexcept { return value; }
708 };
709 @endcode
710
711 @note
712 If this is totally new to you, you might want to take a look at the
713 [documentation][C++14.ice] for `std::integral_constant`.
714
715 One valid answer is that `integral_constant` represents a type-level
716 encoding of a number, or more generally any object of an integral type.
717 For illustration, we could define a successor function on numbers in that
718 representation very easily by using a template alias:
719
720 @code{cpp}
721 template <typename N>
722 using succ = integral_constant<int, N::value + 1>;
723
724 using one = integral_constant<int, 1>;
725 using two = succ<one>;
726 using three = succ<two>;
727 // ...
728 @endcode
729
730 This is the way `integral_constant`s are usually thought of; as _type-level_
731 entities that can be used for template metaprogramming. Another way to see
732 an `integral_constant` is as a runtime object representing a `constexpr` value
733 of an integral type:
734
735 @code{cpp}
736 auto one = integral_constant<int, 1>{};
737 @endcode
738
739 Here, while `one` is not marked as `constexpr`, the abstract value it holds
740 (a `constexpr 1`) is still available at compile-time, because that value is
741 encoded in the type of `one`. Indeed, even if `one` is not `constexpr`, we
742 can use `decltype` to retrieve the compile-time value it represents:
743
744 @code{cpp}
745 auto one = integral_constant<int, 1>{};
746 constexpr int one_constexpr = decltype(one)::value;
747 @endcode
748
749 But why on earth would we want to consider `integral_constant`s as objects
750 instead of type-level entities? To see why, consider how we could now
751 implement the same successor function as before:
752
753 @code{cpp}
754 template <typename N>
755 auto succ(N) {
756   return integral_constant<int, N::value + 1>{};
757 }
758
759 auto one = integral_constant<int, 1>{};
760 auto two = succ(one);
761 auto three = succ(two);
762 // ...
763 @endcode
764
765 Did you notice anything new? The difference is that instead of implementing
766 `succ` at the type-level with a template alias, we're now implementing it at
767 the value-level with a template function. Furthermore, we can now perform
768 compile-time arithmetic using the same syntax as that of normal C++. This
769 way of seeing compile-time entities as objects instead of types is the key
770 to Hana's expressive power.
771
772
773 @subsection tutorial-integral-arithmetic Compile-time arithmetic
774
775 The MPL defines [arithmetic operators][MPL.arithmetic] that can be used to do
776 compile-time computations with `integral_constant`s. A typical example of such
777 an operation is `plus`, which is implemented roughly as:
778
779 @code{cpp}
780 template <typename X, typename Y>
781 struct plus {
782   using type = integral_constant<
783     decltype(X::value + Y::value),
784     X::value + Y::value
785   >;
786 };
787
788 using three = plus<integral_constant<int, 1>,
789                    integral_constant<int, 2>>::type;
790 @endcode
791
792 By viewing `integral_constant`s as objects instead of types, the translation
793 from a metafunction to a function is very straightforward:
794
795 @code{cpp}
796 template <typename V, V v, typename U, U u>
797 constexpr auto
798 operator+(integral_constant<V, v>, integral_constant<U, u>)
799 { return integral_constant<decltype(v + u), v + u>{}; }
800
801 auto three = integral_constant<int, 1>{} + integral_constant<int, 2>{};
802 @endcode
803
804 It is very important to emphasize the fact that this operator does not return
805 a normal integer. Instead, it returns a value-initialized object whose type
806 contains the result of the addition. The only useful information contained in
807 that object is actually in its type, and we're creating an object because it
808 allows us to use this nice value-level syntax. It turns out that we can make
809 this syntax even better by using a [C++14 variable template][C++14.vtemplate]
810 to simplify the creation of an `integral_constant`:
811
812 @code{cpp}
813 template <int i>
814 constexpr integral_constant<int, i> int_c{};
815
816 auto three = int_c<1> + int_c<2>;
817 @endcode
818
819 Now we're talking about a visible gain in expressiveness over the initial
820 type-level approach, aren't we? But there's more; we can also use
821 [C++14 user defined literals][C++14.udl] to make this process even simpler:
822
823 @code{cpp}
824 template <char ...digits>
825 constexpr auto operator"" _c() {
826   // parse the digits and return an integral_constant
827 }
828
829 auto three = 1_c + 3_c;
830 @endcode
831
832 Hana provides its own `integral_constant`s, which define arithmetic operators
833 just like we showed above. Hana also provides variable templates to easily
834 create different kinds of `integral_constant`s: `int_c`, `long_c`, `bool_c`,
835 etc... This allows you to omit the trailing `{}` braces otherwise required to
836 value-initialize these objects. Of course, the `_c` suffix is also provided;
837 it is part of the `hana::literals` namespace, and you must import it into
838 your namespace before using it:
839
840 @code{cpp}
841 using namespace hana::literals;
842
843 auto three = 1_c + 3_c;
844 @endcode
845
846 This way, you may do compile-time arithmetic without having to struggle with
847 awkward type-level idiosyncrasies, and your coworkers will now be able to
848 understand what's going on.
849
850
851 @subsection tutorial-integral-distance Example: Euclidean distance
852
853 To illustrate how good it gets, let's implement a function computing a 2-D
854 euclidean distance at compile-time. As a reminder, the euclidean distance of
855 two points in the 2-D plane is given by
856
857 @f[
858   \mathrm{distance}\left((x_1, y_1), (x_2, y_2)\right)
859       := \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}
860 @f]
861
862 First, here's how it looks like with a type-level approach (using the MPL):
863
864 @snippet example/tutorial/integral.cpp distance-mpl
865
866 Yeah... Now, let's implement it with the value-level approach presented above:
867
868 @snippet example/tutorial/integral.cpp distance-hana
869
870 This version looks arguably cleaner. However, this is not all. Notice how the
871 `distance` function looks exactly as the one you would have written for
872 computing the euclidean distance on dynamic values? Indeed, because we're
873 using the same syntax for dynamic and compile-time arithmetic, generic
874 functions written for one will work for both!
875
876 @snippet example/tutorial/integral.cpp distance-dynamic
877
878 __Without changing any code__, we can use our `distance` function on runtime
879 values and everything just works. Now that's DRY.
880
881
882 @subsection tutorial-integral-branching Compile-time branching
883
884 Once we have compile-time arithmetic, the next thing that might come to mind
885 is compile-time branching. When metaprogramming, it is often useful to have
886 one piece of code be compiled if some condition is true, and a different one
887 otherwise. If you have heard of [static_if][N4461], this should sound very
888 familiar, and indeed it is exactly what we are talking about. Otherwise, if
889 you don't know why we might want to branch at compile-time, consider the
890 following code (adapted from [N4461][]):
891
892 @code{cpp}
893 template <typename T, typename ...Args>
894   std::enable_if_t<std::is_constructible<T, Args...>::value,
895 std::unique_ptr<T>> make_unique(Args&&... args) {
896   return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
897 }
898
899 template <typename T, typename ...Args>
900   std::enable_if_t<!std::is_constructible<T, Args...>::value,
901 std::unique_ptr<T>> make_unique(Args&&... args) {
902   return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
903 }
904 @endcode
905
906 This code creates a `std::unique_ptr` using the correct form of syntax for the
907 constructor. To achieve this, it uses [SFINAE][] and requires two different
908 overloads. Now, anyone sane seeing this for the first time would ask why it
909 is not possible to simply write:
910
911 @code{cpp}
912 template <typename T, typename ...Args>
913 std::unique_ptr<T> make_unique(Args&&... args) {
914   if (std::is_constructible<T, Args...>::value)
915     return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
916   else
917     return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
918 }
919 @endcode
920
921 The reason is that the compiler is required to compile both branches of the
922 `if` statement, regardless of the condition (even though it is known at
923 compile-time). But when `T` is _not_ constructible from `Args...`, the second
924 branch will fail to compile, which will cause a hard compilation error. What
925 we need really is a way to tell the compiler __not to compile__ the second
926 branch when the condition is true, and the first branch when the condition is
927 false.
928
929 To emulate this, Hana provides an `if_` function that works a bit like a
930 normal `if` statement, except except it takes a condition that can be an
931 `IntegralConstant` and returns the one of two values (which may have
932 different types) chosen by the condition. If the condition is true, the
933 first value is returned, and otherwise the second value is returned. A
934 somewhat vain example is the following:
935
936 @code{cpp}
937 auto one_two_three = hana::if_(hana::true_c, 123, "hello");
938 auto hello = hana::if_(hana::false_c, 123, "hello");
939 @endcode
940
941 @note
942 `hana::true_c` and `hana::false_c` are just boolean `IntegralConstant`s
943 representing a compile-time true value and a compile-time false value,
944 respectively.
945
946 Here, `one_two_three` is equal to `123`, and `hello` is equal to `"hello"`.
947 In other words, `if_` is a little bit like the ternary conditional operator
948 `? :`, except that both sides of the `:` can have different types:
949
950 @code{cpp}
951 // fails in both cases because both branches have incompatible types
952 auto one_two_three = hana::true_c ? 123 : "hello";
953 auto hello = hana::false_c ? 123 : "hello";
954 @endcode
955
956 Ok, so this is neat, but how can it actually help us write complete branches
957 that are lazily instantiated by the compiler? The answer is to represent both
958 branches of the `if` statement we'd like to write as generic lambdas, and to
959 use `hana::if_` to return the branch that we'd like to execute. Here's how we
960 could rewrite `make_unique`:
961
962 @snippet example/tutorial/integral-branching.cpp make_unique.if_
963
964 Here, the first value given to `hana::if_` is a generic lambda representing
965 the branch we want to execute if the condition is true, and the second value
966 is the branch we want to execute otherwise. `hana::if_` simply returns the
967 branch chosen by the condition, and we call that branch (which is a generic
968 lambda) immediately with `std::forward<Args>(args)...`. Hence, the proper
969 generic lambda ends up being called, with `x...` being `args...`, and we
970 return the result of that call.
971
972 The reason why this approach works is because the body of each branch can only
973 be instantiated when the types of all `x...` are known. Indeed, since the
974 branch is a generic lambda, the type of the argument is not known until the
975 lambda is called, and the compiler must wait for the types of `x...` to be
976 known before type-checking the lambda's body. Since the erroneous lambda is
977 never called when the condition is not satisfied (`hana::if_` takes care of
978 that), the body of the lambda that would fail is never type-checked and no
979 compilation error happens.
980
981 @note
982 The branches inside the `if_` are lambdas. As such, they really are different
983 functions from the `make_unique` function. The variables appearing inside
984 those branches have to be either captured by the lambdas or passed to them as
985 arguments, and so they are affected by the way they are captured or passed
986 (by value, by reference, etc..).
987
988 Since this pattern of expressing branches as lambdas and then calling them
989 is very common, Hana provides a `eval_if` function whose purpose is to make
990 compile-time branching easier. `eval_if` comes from the fact that in a lambda,
991 one can either receive input data as arguments or capture it from the context.
992 However, for the purpose of emulating a language level `if` statement,
993 implicitly capturing variables from the enclosing scope is usually more
994 natural. Hence, what we would prefer writing is
995
996 @code{cpp}
997 template <typename T, typename ...Args>
998 std::unique_ptr<T> make_unique(Args&&... args) {
999   return hana::if_(std::is_constructible<T, Args...>{},
1000     [&] { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); },
1001     [&] { return std::unique_ptr<T>(new T{std::forward<Args>(args)...}); }
1002   );
1003 }
1004 @endcode
1005
1006 Here, we're capturing the `args...` variables from the enclosing scope, which
1007 prevents us from having to introduce the new `x...` variables and passing them
1008 as arguments to the branches. However, this has two problems. First, this will
1009 not achieve the right result, since `hana::if_` will end up returning a lambda
1010 instead of returning the result of calling that lambda. To fix this, we can use
1011 `hana::eval_if` instead of `hana::if_`:
1012
1013 @code{cpp}
1014 template <typename T, typename ...Args>
1015 std::unique_ptr<T> make_unique(Args&&... args) {
1016   return hana::eval_if(std::is_constructible<T, Args...>{},
1017     [&] { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); },
1018     [&] { return std::unique_ptr<T>(new T{std::forward<Args>(args)...}); }
1019   );
1020 }
1021 @endcode
1022
1023 Here, we capture the enclosing `args...` by reference using `[&]`, and we do
1024 not need to receive any arguments. Also, `hana::eval_if` assumes that its
1025 arguments are branches that can be called, and it will take care of calling
1026 the branch that is selected by the condition. However, this will still cause
1027 a compilation failure, because the bodies of the lambdas are not dependent
1028 anymore, and semantic analysis will be done for both branches even though
1029 only one would end up being used. The solution to this problem is to make
1030 the bodies of the lambdas artificially dependent on something, to prevent the
1031 compiler from being able to perform semantic analysis before the lambda is
1032 actually used. To make this possible, `hana::eval_if` will call the selected
1033 branch with an identity function (a function that returns its argument
1034 unchanged), if the branch accepts such an argument:
1035
1036 @snippet example/tutorial/integral-branching.cpp make_unique.eval_if
1037
1038 Here, the bodies of the branches take an additional argument called `_` by
1039 convention. This argument will be provided by `hana::eval_if` to the branch
1040 that was selected. Then, we use `_` as a function on the variables that we
1041 want to make dependent within the body of each branch. What happens is that
1042 `_` will always be a function that returns its argument unchanged. However,
1043 the compiler can't possibly know it before the lambda has actually been called,
1044 so it can't know the type of `_(args)`. This prevents the compiler from being
1045 able to perform semantic analysis, and no compilation error happens. Plus,
1046 since `_(x)` is guaranteed to be equivalent to `x`, we know that we're not
1047 actually changing the semantics of the branches by using this trick.
1048
1049 While using this trick may seem cumbersome, it can be very useful when dealing
1050 with many variables inside a branch. Furthermore, it is not required to wrap
1051 all variables with `_`; only variables that are involved in an expression whose
1052 type-checking has to be delayed must be wrapped, but the other ones are not
1053 required. There are still a few things to know about compile-time branching
1054 in Hana, but you can dig deeper by looking at the reference for `hana::eval_if`,
1055 `hana::if_` and `hana::lazy`.
1056
1057
1058 @subsection tutorial-integral-more Why stop here?
1059
1060 Why should we limit ourselves to arithmetic operations and branching? When you
1061 start considering `IntegralConstant`s as objects, it becomes sensible to augment
1062 their interface with more functions that are generally useful. For example,
1063 Hana's `IntegralConstant`s define a `times` member function that can be used
1064 to invoke a function a certain number of times, which is especially useful
1065 for loop unrolling:
1066
1067 @code{cpp}
1068 __attribute__((noinline)) void f() { }
1069
1070 int main() {
1071   hana::int_c<10>.times(f);
1072 }
1073 @endcode
1074
1075 In the above code, the 10 calls to `f` are expanded at compile-time. In other
1076 words, this is equivalent to writing
1077
1078 @code{cpp}
1079 f(); f(); ... f(); // 10 times
1080 @endcode
1081
1082 @note
1083 Always [be careful][Chandler.MeetingC++] about manually unrolling loops or
1084 doing other such optimizations manually. In most cases, your compiler is
1085 probably better than you at optimizing. When in doubt, benchmark.
1086
1087 Another nice use of `IntegralConstant`s is to define good-looking operators
1088 for indexing heterogeneous sequences. Whereas `std::tuple` must be accessed
1089 with `std::get`, `hana::tuple` can be accessed using the familiar `operator[]`
1090 used for standard library containers:
1091
1092 @code{cpp}
1093 auto values = hana::make_tuple(1, 'x', 3.4f);
1094 char x = values[1_c];
1095 @endcode
1096
1097 How this works is very simple. Basically, `hana::tuple` defines an `operator[]`
1098 taking an `IntegralConstant` instead of a normal integer, in a way similar to
1099
1100 @code{cpp}
1101 template <typename N>
1102 constexpr decltype(auto) operator[](N const&) {
1103   return std::get<N::value>(*this);
1104 }
1105 @endcode
1106
1107 This is the end of the section on `IntegralConstant`s. This section introduced
1108 the feel behind Hana's new way of metaprogramming; if you liked what you've
1109 seen so far, the rest of this tutorial should feel just like home.
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120 @section tutorial-type Type computations
1121
1122 ------------------------------------------------------------------------------
1123 At this point, if you are interested in doing type-level computations as with
1124 the MPL, you might be wondering how is Hana going to help you. Do not despair.
1125 Hana provides a way to perform type-level computations with a great deal of
1126 expressiveness by representing types as values, just like we represented
1127 compile-time numbers as values. This is a completely new way of approaching
1128 metaprogramming, and you should try to set your old MPL habits aside for a bit
1129 if you want to become proficient with Hana.
1130
1131 However, please be aware that modern C++ features like [auto-deduced return type]
1132 [C++14.auto_rt] remove the need for type computations in many cases. Hence,
1133 before even considering to do a type computation, you should ask yourself
1134 whether there's a simpler way to achieve what you're trying to achieve. In
1135 most cases, the answer will be yes. However, when the answer is no, Hana will
1136 provide you with nuclear-strength facilities to do what needs to be done.
1137
1138
1139 @subsection tutorial-type-objects Types as objects
1140
1141 The key behind Hana's approach to type-level computations is essentially the
1142 same as the approach to compile-time arithmetic. Basically, the idea is to
1143 represent compile-time entities as objects by wrapping them into some kind of
1144 container. For `IntegralConstant`s, the compile-time entities were constant
1145 expressions of an integral type and the wrapper we used was `integral_constant`.
1146 In this section, the compile-time entities will be types and the wrapper we'll
1147 be using is called `type`. Just like we did for `IntegralConstant`s, let's
1148 start by defining a dummy template that could be used to represent a type:
1149
1150 @code{cpp}
1151 template <typename T>
1152 struct basic_type {
1153   // empty (for now)
1154 };
1155
1156 basic_type<int> Int{};
1157 basic_type<char> Char{};
1158 // ...
1159 @endcode
1160
1161 @note
1162 We're using the name `basic_type` here because we're only building a naive
1163 version of the actual functionality provided by Hana.
1164
1165 While this may seem completely useless, it is actually enough to start writing
1166 metafunctions that look like functions. Indeed, consider the following
1167 alternate implementations of `std::add_pointer` and `std::is_pointer`:
1168
1169 @code{cpp}
1170 template <typename T>
1171 constexpr basic_type<T*> add_pointer(basic_type<T> const&)
1172 { return {}; }
1173
1174 template <typename T>
1175 constexpr auto is_pointer(basic_type<T> const&)
1176 { return hana::bool_c<false>; }
1177
1178 template <typename T>
1179 constexpr auto is_pointer(basic_type<T*> const&)
1180 { return hana::bool_c<true>; }
1181 @endcode
1182
1183 We've just written metafunctions that look like functions, just like we wrote
1184 compile-time arithmetic metafunctions as heterogeneous C++ operators in the
1185 previous section. Here's how we can use them:
1186
1187 @code{cpp}
1188 basic_type<int> t{};
1189 auto p = add_pointer(t);
1190 BOOST_HANA_CONSTANT_CHECK(is_pointer(p));
1191 @endcode
1192
1193 Notice how we can now use a normal function call syntax to perform type-level
1194 computations? This is analogous to how using values for compile-time numbers
1195 allowed us to use normal C++ operators to perform compile-time computations.
1196 Like we did for `integral_constant`, we can also go one step further and use
1197 C++14 variable templates to provide syntactic sugar for creating types:
1198
1199 @code{cpp}
1200 template <typename T>
1201 constexpr basic_type<T> type_c{};
1202
1203 auto t = type_c<int>;
1204 auto p = add_pointer(t);
1205 BOOST_HANA_CONSTANT_CHECK(is_pointer(p));
1206 @endcode
1207
1208 @note
1209 This is not exactly how the `hana::type_c` variable template is implemented
1210 because of some subtleties; things were dumbed down here for the sake of the
1211 explanation. Please check the reference for `hana::type` to know exactly
1212 what you can expect from a `hana::type_c<...>`.
1213
1214
1215 @subsection tutorial-type-benefits Benefits of this representation
1216
1217 But what does that buy us? Well, since a `type_c<...>` is just an object, we
1218 can store it in a heterogeneous sequence like a tuple, we can move it around
1219 and pass it to (or return it from) functions, and we can do basically anything
1220 else that requires an object:
1221
1222 @snippet example/tutorial/type.cpp tuple
1223
1224 @note
1225 Writing `make_tuple(type_c<T>...)` can be annoying when there are several types.
1226 For this reason, Hana provides the `tuple_t<T...>` variable template, which is
1227 syntactic sugar for `make_tuple(type_c<T>...)`.
1228
1229 Also, notice that since the above tuple is really just a normal heterogeneous
1230 sequence, we can apply heterogeneous algorithms on that sequence just like we
1231 could on a tuple of `int`s, for example. Furthermore, since we're just
1232 manipulating objects, we can now use the full language instead of just the
1233 small subset available at the type-level. For example, consider the task of
1234 removing all the types that are not a reference or a pointer from a sequence
1235 of types. With the MPL, we would have to use a placeholder expression to
1236 express the predicate, which is clunky:
1237
1238 @snippet example/tutorial/type.cpp filter.MPL
1239
1240 Now, since we're manipulating objects, we can use the full language and use a
1241 generic lambda instead, which leads to much more readable code:
1242
1243 @snippet example/tutorial/type.cpp filter.Hana
1244
1245 Since Hana handles all heterogeneous containers uniformly, this approach of
1246 representing types as values also has the benefit that a single library is
1247 now needed for both heterogeneous computations and type level computations.
1248 Indeed, whereas we would normally need two different libraries to perform
1249 almost identical tasks, we now need a single library. Again, consider the
1250 task of filtering a sequence with a predicate. With MPL and Fusion, this
1251 is what we must do:
1252
1253 @snippet example/tutorial/type.cpp single_library.then
1254
1255 With Hana, a single library is required. Notice how we use the same `filter`
1256 algorithm and the same container, and only tweak the predicate so it can
1257 operate on values:
1258
1259 @snippet example/tutorial/type.cpp single_library.Hana
1260
1261 But that is not all. Indeed, having a unified syntax for type-level and
1262 value-level computations allows us to achieve greater consistency in the
1263 interface of heterogeneous containers. For example, consider the simple
1264 task of creating a heterogeneous map associating types to values, and then
1265 accessing an element of it. With Fusion, what's happening is far from obvious
1266 to the untrained eye:
1267
1268 @snippet example/tutorial/type.cpp make_map.Fusion
1269
1270 However, with a unified syntax for types and values, the same thing becomes
1271 much clearer:
1272
1273 @snippet example/tutorial/type.cpp make_map.Hana
1274
1275 While Hana's way takes more lines of codes, it is also arguably more readable
1276 and closer to how someone would expect to initialize a map.
1277
1278
1279 @subsection tutorial-type-working Working with this representation
1280
1281 So far, we can represent types as values and perform type-level computations
1282 on those objects using the usual C++ syntax. This is nice, but it is not very
1283 useful because we have no way to get back a normal C++ type from an object
1284 representation. For example, how could we declare a variable whose type is the
1285 result of a type computation?
1286
1287 @code{cpp}
1288 auto t = add_pointer(hana::type_c<int>); // could be a complex type computation
1289 using T = the-type-represented-by-t;
1290
1291 T var = ...;
1292 @endcode
1293
1294 Right now, there is no easy way to do it. To make this easier to achieve, we
1295 enrich the interface of the `basic_type` container that we defined above.
1296 Instead of being an empty `struct`, we now define it as
1297
1298 @code{cpp}
1299 template <typename T>
1300 struct basic_type {
1301   using type = T;
1302 };
1303 @endcode
1304
1305 @note
1306 This is equivalent to making `basic_type` a metafunction in the MPL sense.
1307
1308 This way, we can use `decltype` to easily access the actual C++ type
1309 represented by a `type_c<...>` object:
1310
1311 @code{cpp}
1312 auto t = add_pointer(hana::type_c<int>);
1313 using T = decltype(t)::type; // fetches basic_type<T>::type
1314
1315 T var = ...;
1316 @endcode
1317
1318 In general, doing type-level metaprogramming with Hana is a three step process:
1319
1320 1. Represent types as objects by wrapping them with `hana::type_c<...>`
1321 2. Perform type transformations with value syntax
1322 3. Unwrap the result with `decltype(...)::%type`
1323
1324 Now, you must be thinking that this is incredibly cumbersome. In reality, it
1325 is very manageable for several reasons. First, this wrapping and unwrapping
1326 only needs to happen at some very thin boundaries.
1327
1328 @code{cpp}
1329 auto t = hana::type_c<T>;
1330 auto result = huge_type_computation(t);
1331 using Result = decltype(result)::type;
1332 @endcode
1333
1334 Furthermore, since you get the advantage of working with objects (without
1335 having to wrap/unwrap) inside the computation, the cost of wrapping and
1336 unwrapping is amortized on the whole computation. Hence, for complex type
1337 computations, the syntactic noise of this three step process quickly becomes
1338 negligible in light of the expressiveness gain of working with values inside
1339 that computation. Also, using values instead of types means that we can avoid
1340 typing `typename` and `template` all around the place, which accounted for a
1341 lot of syntactic noise in classic metaprogramming.
1342
1343 Another point is that the three full steps are not always required. Indeed,
1344 sometimes one just needs to do a type-level computation and query something
1345 about the result, without necessarily fetching the result as a normal C++ type:
1346
1347 @code{cpp}
1348 auto t = hana::type_c<T>;
1349 auto result = type_computation(t);
1350 BOOST_HANA_CONSTANT_CHECK(is_pointer(result)); // third step skipped
1351 @endcode
1352
1353 In this case, we were able to skip the third step because we did not need to
1354 access the actual type represented by `result`. In other cases, the first step
1355 can be avoided, like when using `tuple_t`, which has no more syntactic noise
1356 than any other pure type-level approach:
1357
1358 @snippet example/tutorial/type.cpp skip_first_step
1359
1360 For skeptical readers, let's consider the task of finding the smallest type
1361 in a sequence of types. This is a very good example of a short type-only
1362 computation, which is where we would expect the new paradigm to suffer the
1363 most. As you will see, things stay manageable even for small computations.
1364 First, let's implement it with the MPL:
1365
1366 @snippet example/tutorial/type.cpp smallest.MPL
1367
1368 The result is quite readable (for anyone familiar with the MPL). Let's now
1369 implement the same thing using Hana:
1370
1371 @snippet example/tutorial/type.cpp smallest.Hana
1372
1373 As you can witness, the syntactic noise of the 3-step process is almost
1374 completely hidden by the rest of the computation.
1375
1376
1377 @subsection tutorial-type-lifting The generic lifting process
1378
1379 The first type-level computation that we introduced in the form of a function
1380 looked like:
1381
1382 @code{cpp}
1383 template <typename T>
1384 constexpr auto add_pointer(hana::basic_type<T> const&) {
1385   return hana::type<T*>;
1386 }
1387 @endcode
1388
1389 While it looks more complicated, we could also write it as:
1390
1391 @code{cpp}
1392 template <typename T>
1393 constexpr auto add_pointer(hana::basic_type<T> const&) {
1394   return hana::type_c<typename std::add_pointer<T>::type>;
1395 }
1396 @endcode
1397
1398 However, this implementation emphasizes the fact that we're really emulating
1399 an existing metafunction and simply representing it as a function. In other
1400 words, we're _lifting_ a metafunction (`std::add_pointer`) to the world of
1401 values by creating our own `add_pointer` function. It turns out that this
1402 lifting process is a generic one. Indeed, given any metafunction, we could
1403 write almost the same thing:
1404
1405 @code{cpp}
1406 template <typename T>
1407 constexpr auto add_const(hana::basic_type<T> const&)
1408 { return hana::type_c<typename std::add_const<T>::type>; }
1409
1410 template <typename T>
1411 constexpr auto add_volatile(hana::basic_type<T> const&)
1412 { return hana::type_c<typename std::add_volatile<T>::type>; }
1413
1414 template <typename T>
1415 constexpr auto add_lvalue_reference(hana::basic_type<T> const&)
1416 { return hana::type_c<typename std::add_lvalue_reference<T>::type>; }
1417
1418 // etc...
1419 @endcode
1420
1421 This mechanical transformation is easy to abstract into a generic lifter
1422 that can handle any [MPL Metafunction][MPL.metafunction] as follows:
1423
1424 @snippet example/tutorial/type.cpp metafunction1
1425
1426 More generally, we'll want to allow metafunctions with any number of
1427 arguments, which brings us to the following less naive implementation:
1428
1429 @snippet example/tutorial/type.cpp metafunction2
1430
1431 Hana provides a similar generic metafunction lifter called `hana::metafunction`.
1432 One small improvement is that `hana::metafunction<F>` is a function object
1433 instead of an overloaded function, so one can pass it to higher-order
1434 algorithms. It is also a model of the slightly more powerful concept of
1435 `Metafunction`, but this can safely be ignored for now. The process we
1436 explored in this section does not only apply to metafunctions; it also
1437 applies to templates. Indeed, we could define:
1438
1439 @snippet example/tutorial/type.cpp template_
1440
1441 Hana provides a generic lifter for templates named `hana::template_`, and it
1442 also provides a generic lifter for [MPL MetafunctionClasses][MPL.mfc] named
1443 `hana::metafunction_class`. This gives us a way to uniformly represent "legacy"
1444 type-level computations as functions, so that any code written using a classic
1445 type-level metaprogramming library can almost trivially be used with Hana. For
1446 example, say you have a large chunk of MPL-based code and you'd like to
1447 interface with Hana. The process of doing so is no harder than wrapping your
1448 metafunctions with the lifter provided by Hana:
1449
1450 @code{cpp}
1451 template <typename T>
1452 struct legacy {
1453   using type = ...; // something you really don't want to mess with
1454 };
1455
1456 auto types = hana::make_tuple(...);
1457 auto use = hana::transform(types, hana::metafunction<legacy>);
1458 @endcode
1459
1460 However, note that not all type-level computations can be lifted as-is with
1461 the tools provided by Hana. For example, `std::extent` can't be lifted because
1462 it requires non-type template parameters. Since there is no way to deal with
1463 non-type template parameters uniformly in C++, one must resort to using a
1464 hand-written function object specific to that type-level computation:
1465
1466 @snippet example/tutorial/type.cpp extent
1467
1468 @note
1469 Do not forget to include the bridge header for `std::integral_constant`s
1470 (`<boost/hana/ext/std/integral_constant.hpp>`) when using type traits from
1471 `<type_traits>` directly.
1472
1473 In practice, however, this should not be a problem since the vast majority
1474 of type-level computations can be lifted easily. Finally, since metafunctions
1475 provided by the `<type_traits>` header are used so frequently, Hana provides
1476 a lifted version for every one of them. Those lifted traits are in the
1477 `hana::traits` namespace, and they live in the `<boost/hana/traits.hpp>` header:
1478
1479 @snippet example/tutorial/type.cpp traits
1480
1481 This is the end of the section on type computations. While this new paradigm
1482 for type level programming might be difficult to grok at first, it will make
1483 more sense as you use it more and more. You will also come to appreciate how
1484 it blurs the line between types and values, opening new exciting possibilities
1485 and simplifying many tasks.
1486
1487 @note
1488 Curious or skeptical readers should consider checking the minimal
1489 reimplementation of the MPL presented in the [appendices]
1490 (@ref tutorial-appendix-MPL).
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501 @section tutorial-introspection Introspection
1502
1503 ------------------------------------------------------------------------------
1504 Static introspection, as we will discuss it here, is the ability of a program
1505 to examine the type of an object at compile-time. In other words, it is a
1506 programmatic interface to interact with types at compile-time. For example,
1507 have you ever wanted to check whether some unknown type has a member named
1508 `foo`? Or perhaps at some point you have needed to iterate on the members
1509 of a `struct`?
1510
1511 @code{cpp}
1512 struct Person {
1513   std::string name;
1514   int age;
1515 };
1516
1517 Person john{"John", 30};
1518 for (auto& member : john)
1519   std::cout << member.name << ": " << member.value << std::endl;
1520
1521 // name: John
1522 // age: 30
1523 @endcode
1524
1525 If you have written a bit of templates in your life, chances are very high
1526 that you came across the first problem of checking for a member. Also, anyone
1527 having tried to implement object serialization or even just pretty printing
1528 has come across the second problem. In most dynamic languages like Python,
1529 Ruby or JavaScript, these problems are completely solved and introspection is
1530 used every day by programmers to make a lot of tasks simpler. However, as a
1531 C++ programmer, we do not have language support for those things, which makes
1532 several tasks much harder than they should be. While language support would
1533 likely be needed to properly tackle this problem, Hana makes some common
1534 introspection patterns much more accessible.
1535
1536
1537 @subsection tutorial-introspection-is_valid Checking expression validity
1538
1539 Given an object of an unknown type, it is sometimes desirable to check
1540 whether this object has a member (or member function) with some name.
1541 This can be used to perform sophisticated flavors of overloading. For
1542 example, consider the problem of calling a `toString` method on objects
1543 that support it, but providing another default implementation for objects
1544 that do not support it:
1545
1546 @code{cpp}
1547 template <typename T>
1548 std::string optionalToString(T const& obj) {
1549   if (obj.toString() is a valid expression)
1550     return obj.toString();
1551   else
1552     return "toString not defined";
1553 }
1554 @endcode
1555
1556 @note
1557 While most use cases for this technique will be addressed by [concepts lite]
1558 [C++17.clite] in future revisions of the standard, there will still be cases
1559 where a quick and dirty check is more convenient than creating a full blown
1560 concept.
1561
1562 How could we implement a check for the validity of `obj.toString()` as above
1563 in a generic fashion (so it can be reused in other functions, for example)?
1564 Normally, we would be stuck writing some kind of SFINAE-based detection:
1565
1566 @snippet example/tutorial/introspection.cpp has_toString.then
1567
1568 This works, but the intent is not very clear and most people without a deep
1569 knowledge of template metaprogramming would think this is black magic. Then,
1570 we could implement `optionalToString` as
1571
1572 @code{cpp}
1573 template <typename T>
1574 std::string optionalToString(T const& obj) {
1575   if (has_toString<T>::value)
1576     return obj.toString();
1577   else
1578     return "toString not defined";
1579 }
1580 @endcode
1581
1582 @note
1583 Of course, this implementation won't actually work because both branches of
1584 the `if` statement will be compiled. If `obj` does not have a `toString`
1585 method, the compilation of the `if` branch will fail. We will address
1586 this issue in a moment.
1587
1588 Instead of the above SFINAE trick, Hana provides a `is_valid` function that
1589 can be combined with [C++14 generic lambdas][C++14.glambda] to obtain a much
1590 cleaner implementation of the same thing:
1591
1592 @snippet example/tutorial/introspection.cpp has_toString.now
1593
1594 This leaves us with a function object `has_toString` which returns whether the
1595 given expression is valid on the argument we pass to it. The result is returned
1596 as an `IntegralConstant`, so `constexpr`-ness is not an issue here because the
1597 result of the function is represented as a type anyway. Now, in addition to
1598 being less verbose (that's a one liner!), the intent is much clearer. Other
1599 benefits are the fact that `has_toString` can be passed to higher order
1600 algorithms and it can also be defined at function scope, so there is no need
1601 to pollute the namespace scope with implementation details. Here is how we
1602 would now write `optionalToString`:
1603
1604 @code{cpp}
1605 template <typename T>
1606 std::string optionalToString(T const& obj) {
1607   if (has_toString(obj))
1608     return obj.toString();
1609   else
1610     return "toString not defined";
1611 }
1612 @endcode
1613
1614 Much cleaner, right? However, as we said earlier, this implementation won't
1615 actually work because both branches of the `if` always have to be compiled,
1616 regardless of whether `obj` has a `toString` method. There are several
1617 possible options, but the most classical one is to use `std::enable_if`:
1618
1619 @snippet example/tutorial/introspection.cpp optionalToString.then
1620
1621 @note
1622 We're using the fact that `has_toString` returns an `IntegralConstant` to
1623 write `decltype(...)::%value`, which is a constant expression. For some
1624 reason, `has_toString(obj)` is not considered a constant expression, even
1625 though I think it should be one because we never read from `obj` (see the
1626 section on [advanced constexpr](@ref tutorial-appendix-constexpr)).
1627
1628 While this implementation is perfectly valid, it is still pretty cumbersome
1629 because it requires writing two different functions and going through the
1630 hoops of SFINAE explicitly by using `std::enable_if`. However, as you might
1631 remember from the section on [compile-time branching](@ref tutorial-integral-branching),
1632 Hana provides an `if_` function that can be used to emulate the functionality
1633 of [static_if][N4461]. Here is how we could write `optionalToString` with
1634 `hana::if_`:
1635
1636 @snippet example/tutorial/introspection.cpp optionalToString
1637
1638 Now, the previous example covered only the specific case of checking for the
1639 presence of a non-static member function. However, `is_valid` can be used to
1640 detect the validity of almost any kind of expression. For completeness, we
1641 now present a list of common use cases for validity checking along with how
1642 to use `is_valid` to implement them.
1643
1644
1645 @subsubsection tutorial-introspection-is_valid-non_static Non-static members
1646
1647 The first idiom we'll look at is checking for the presence of a non-static
1648 member. We can do it in a similar way as we did for the previous example:
1649
1650 @snippet example/tutorial/introspection.cpp non_static_member_from_object
1651
1652 Notice how we cast the result of `x.member` to `void`? This is to make sure
1653 that our detection also works for types that can't be returned from functions,
1654 like array types. Also, it is important to use a reference as the parameter to
1655 our generic lambda, because that would otherwise require `x` to be
1656 [CopyConstructible][], which is not what we're trying to check. This approach
1657 is simple and the most convenient when an object is available. However, when
1658 the checker is intended to be used with no object around, the following
1659 alternate implementation can be better suited:
1660
1661 @snippet example/tutorial/introspection.cpp non_static_member_from_type
1662
1663 This validity checker is different from what we saw earlier because the
1664 generic lambda is not expecting an usual object anymore; it is now expecting
1665 a `type` (which is an object, but still represents a type). We then use the
1666 `hana::traits::declval` _lifted metafunction_ from the `<boost/hana/traits.hpp>`
1667 header to create an rvalue of the type represented by `t`, which we can then
1668 use to check for a non-static member. Finally, instead of passing an actual
1669 object to `has_member` (like `Foo{}` or `Bar{}`), we now pass a `type_c<...>`.
1670 This implementation is ideal for when no object is lying around.
1671
1672
1673 @subsubsection tutorial-introspection-is_valid-static Static members
1674
1675 Checking for a static member is easy, and it is provided for completeness:
1676
1677 @snippet example/tutorial/introspection.cpp static_member
1678
1679 Again, we expect a `type` to be passed to the checker. Inside the generic
1680 lambda, we use `decltype(t)::%type` to fetch the actual C++ type represented
1681 by the `t` object, as explained in the section on [type computations]
1682 (@ref tutorial-type-working). Then, we fetch the static member inside
1683 that type and cast it to `void`, for the same reason as we did for non-static
1684 members.
1685
1686
1687 @subsubsection tutorial-introspection-is_valid-typename Nested type names
1688
1689 Checking for a nested type name is not hard, but it is slightly more
1690 convoluted than the previous cases:
1691
1692 @snippet example/tutorial/introspection.cpp nested_type_name
1693
1694 One might wonder why we use `-> hana::type<typename-expression>` instead
1695 of simply `-> typename-expression`. Again, the reason is that we want to
1696 support types that can't be returned from functions, like array types or
1697 incomplete types.
1698
1699
1700 @subsubsection tutorial-introspection-is_valid-template Nested templates
1701
1702 Checking for a nested template name is similar to checking for a nested type
1703 name, except we use the `template_<...>` variable template instead of
1704 `type<...>` in the generic lambda:
1705
1706 @snippet example/tutorial/introspection.cpp nested_template
1707
1708
1709 @subsection tutorial-introspection-sfinae Taking control of SFINAE
1710
1711 Doing something only if an expression is well-formed is a very common pattern
1712 in C++. Indeed, the `optionalToString` function is just one instance of the
1713 following pattern, which is very general:
1714
1715 @code{cpp}
1716 template <typename T>
1717 auto f(T x) {
1718   if (some expression involving x is well-formed)
1719     return something involving x;
1720   else
1721     return something else;
1722 }
1723 @endcode
1724
1725 To encapsulate this pattern, Hana provides the `sfinae` function, which allows
1726 executing an expression, but only if it is well-formed:
1727
1728 @snippet example/tutorial/introspection.sfinae.cpp maybe_add
1729
1730 Here, we create a `maybe_add` function, which is simply a generic lambda
1731 wrapped with Hana's `sfinae` function. `maybe_add` is a function which takes
1732 two inputs and returns `just` the result of the generic lambda if that call
1733 is well-formed, and `nothing` otherwise. `just(...)` and `nothing` both belong
1734 to a type of container called `hana::optional`, which is essentially a
1735 compile-time `std::optional`. All in all, `maybe_add` is morally equivalent
1736 to the following function returning a `std::optional`, except that the check
1737 is done at compile-time:
1738
1739 @code{cpp}
1740 auto maybe_add = [](auto x, auto y) {
1741   if (x + y is well formed)
1742     return std::optional<decltype(x + y)>{x + y};
1743   else
1744     return std::optional<???>{};
1745 };
1746 @endcode
1747
1748 It turns out that we can take advantage of `sfinae` and `optional` to
1749 implement the `optionalToString` function as follows:
1750
1751 @snippet example/tutorial/introspection.sfinae.cpp optionalToString.sfinae
1752
1753 First, we wrap `toString` with the `sfinae` function. Hence, `maybe_toString`
1754 is a function which either returns `just(x.toString())` if that is well-formed,
1755 or `nothing` otherwise. Secondly, we use the `.value_or()` function to extract
1756 the optional value from the container. If the optional value is `nothing`,
1757 `.value_or()` returns the default value given to it; otherwise, it returns the
1758 value inside the `just` (here `x.toString()`). This way of seeing SFINAE as a
1759 special case of computations that might fail is very clean and powerful,
1760 especially since `sfinae`'d functions can be combined through the
1761 `hana::optional` `Monad`, which is left to the reference documentation.
1762
1763
1764 @subsection tutorial-introspection-adapting Introspecting user-defined types
1765
1766 Have you ever wanted to iterate over the members of a user-defined type? The
1767 goal of this section is to show you how Hana can be used to do it quite easily.
1768 To allow working with user-defined types, Hana defines the `Struct` concept.
1769 Once a user-defined type is a model of that concept, one can iterate over the
1770 members of an object of that type and query other useful information. To turn
1771 a user-defined type into a `Struct`, a couple of options are available. First,
1772 you may define the members of your user-defined type with the
1773 `BOOST_HANA_DEFINE_STRUCT` macro:
1774
1775 @snippet example/tutorial/introspection.adapt.cpp BOOST_HANA_DEFINE_STRUCT
1776
1777 This macro defines two members (`name` and `age`) with the given types. Then,
1778 it defines some boilerplate inside a `Person::hana` nested `struct`, which is
1779 required to make `Person` a model of the `Struct` concept. No constructors are
1780 defined (so [POD-ness][POD] is retained), the members are defined in the same
1781 order as they appear here and the macro can be used with template `struct`s
1782 just as well, and at any scope. Also note that you are free to add more
1783 members to the `Person` type after or before you use the macro. However,
1784 only members defined with the macro will be picked up when introspecting the
1785 `Person` type. Easy enough? Now, a `Person` can be accessed programmatically:
1786
1787 @snippet example/tutorial/introspection.adapt.cpp for_each
1788
1789 Iteration over a `Struct` is done as if the `Struct` was a sequence of pairs,
1790 where the first element of a pair is the key associated to a member, and the
1791 second element is the member itself. When a `Struct` is defined through the
1792 `BOOST_HANA_DEFINE_STRUCT` macro, the key associated to any member is a
1793 compile-time `hana::string` representing the name of that member. This is why
1794 the function used with `for_each` takes a single argument `pair`, and then
1795 uses `first` and `second` to access the subparts of the pair. Also, notice
1796 how the `to<char const*>` function is used on the name of the member? This
1797 converts the compile-time string to a `constexpr char const*` so it can
1798 `cout`ed. Since it can be annoying to always use `first` and `second` to
1799 fetch the subparts of the pair, we can also use the `fuse` function to wrap
1800 our lambda and make it a binary lambda instead:
1801
1802 @snippet example/tutorial/introspection.adapt.cpp for_each.fuse
1803
1804 Now, it looks much cleaner. As we just mentioned, `Struct`s are seen as a kind
1805 of sequence of pairs for the purpose of iteration. In fact, a `Struct` can
1806 even be searched like an associative data structure whose keys are the names
1807 of the members, and whose values are the members themselves:
1808
1809 @snippet example/tutorial/introspection.adapt.cpp at_key
1810
1811 @note
1812 The `_s` user-defined literal creates a compile-time `hana::string`. It is
1813 located in the `boost::hana::literals` namespace. Note that it is not part
1814 of the standard yet, but it is supported by Clang and GCC. If you want to
1815 stay 100% standard, you can use the `BOOST_HANA_STRING` macro instead.
1816
1817 The main difference between a `Struct` and a `hana::map` is that a map can be
1818 modified (keys can be added and removed), while a `Struct` is immutable.
1819 However, you can easily convert a `Struct` into a `hana::map` with `to<map_tag>`,
1820 and then you can manipulate it in a more flexible way.
1821
1822 @snippet example/tutorial/introspection.adapt.cpp to<map_tag>
1823
1824 Using the `BOOST_HANA_DEFINE_STRUCT` macro to adapt a `struct` is convenient,
1825 but sometimes one can't modify the type that needs to be adapted. In these
1826 cases, the `BOOST_HANA_ADAPT_STRUCT` macro can be used to adapt a `struct` in
1827 a ad-hoc manner:
1828
1829 @snippet example/tutorial/introspection.adapt.cpp BOOST_HANA_ADAPT_STRUCT
1830
1831 @note
1832 The `BOOST_HANA_ADAPT_STRUCT` macro must be used at global scope.
1833
1834 The effect is exactly the same as with the `BOOST_HANA_DEFINE_STRUCT` macro,
1835 except you do not need to modify the type you want to adapt, which is
1836 sometimes useful. Finally, it is also possible to define custom accessors
1837 by using the `BOOST_HANA_ADAPT_ADT` macro:
1838
1839 @snippet example/tutorial/introspection.adapt.cpp BOOST_HANA_ADAPT_ADT
1840
1841 This way, the names used to access the members of the `Struct` will be those
1842 specified, and the associated function will be called on the `Struct` when
1843 retrieving that member. Before we move on to a concrete example of using these
1844 introspection features, it should also be mentioned that `struct`s can be
1845 adapted without using macros. This advanced interface for defining `Struct`s
1846 can be used for example to specify keys that are not compile-time strings.
1847 The advanced interface is described in the documentation of the `Struct`
1848 concept.
1849
1850
1851 @subsection tutorial-introspection-json Example: generating JSON
1852
1853 Let's now move on with a concrete example of using the introspection
1854 capabilities we just presented for printing custom objects as JSON.
1855 Our end goal is to have something like this:
1856
1857 @snippet example/tutorial/introspection.json.cpp usage
1858
1859 And the output, after passing it through a JSON pretty-printer,
1860 should look like
1861
1862 @code{.json}
1863 [
1864   {
1865     "name": "John",
1866     "last_name": "Doe",
1867     "age": 30
1868   },
1869   {
1870     "brand": "Audi",
1871     "model": "A4"
1872   },
1873   {
1874     "brand": "BMW",
1875     "model": "Z3"
1876   }
1877 ]
1878 @endcode
1879
1880 First, let's define a couple of utility functions to make string manipulation
1881 easier:
1882
1883 @snippet example/tutorial/introspection.json.cpp utilities
1884
1885 The `quote` and the `to_json` overloads are pretty self-explanatory. The
1886 `join` function, however, might need a bit of explanation. Basically, the
1887 `intersperse` function takes a sequence and a separator, and returns a new
1888 sequence with the separator in between each pair of elements of the original
1889 sequence. In other words, we take a sequence of the form `[x1, ..., xn]` and
1890 turn it into a sequence of the form `[x1, sep, x2, sep, ..., sep, xn]`.
1891 Finally, we fold the resulting sequence with the `_ + _` function object,
1892 which is equivalent to `std::plus<>{}`. Since our sequence contains
1893 `std::string`s (we assume it does), this has the effect of concatenating
1894 all the strings of the sequence into one big string. Now, let's define
1895 how to print a `Sequence`:
1896
1897 @snippet example/tutorial/introspection.json.cpp Sequence
1898
1899 First, we use the `transform` algorithm to turn our sequence of objects into
1900 a sequence of `std::string`s in JSON format. Then, we join that sequence with
1901 commas and we enclose it with `[]` to denote a sequence in JSON notation.
1902 Simple enough? Let's now take a look at how to print user-defined types:
1903
1904 @snippet example/tutorial/introspection.json.cpp Struct
1905
1906 Here, we use the `keys` method to retrieve a `tuple` containing the names of
1907 the members of the user-defined type. Then, we `transform` that sequence into
1908 a sequence of `"name" : member` strings, which we then `join` and enclose with
1909 `{}`, which is used to denote objects in JSON notation. And that's it!
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920 @section tutorial-containers Generalities on containers
1921
1922 ------------------------------------------------------------------------------
1923 This section explains several important notions about Hana's containers: how
1924 to create them, the lifetime of their elements and other concerns.
1925
1926
1927 @subsection tutorial-containers-creating Container creation
1928
1929 While the usual way of creating an object in C++ is to use its constructor,
1930 heterogeneous programming makes things a bit more complicated. Indeed, in
1931 most cases, one is not interested in (or even aware of) the actual type of
1932 the heterogeneous container to be created. At other times, one could write
1933 out that type explicitly, but it would be redundant or cumbersome to do so.
1934 For this reason, Hana uses a different approach borrowed from `std::make_tuple`
1935 to create new containers. Much like one can create a `std::tuple` with
1936 `std::make_tuple`, a `hana::tuple` can be created with `hana::make_tuple`.
1937 However, more generally, containers in Hana may be created with the `make`
1938 function:
1939
1940 @snippet example/tutorial/containers.cpp make<tuple_tag>
1941
1942 In fact, `make_tuple` is just a shortcut for `make<tuple_tag>` so you don't
1943 have to type `boost::hana::make<boost::hana::tuple_tag>` when you are out of
1944 Hana's namespace. Simply put, `make<...>` is is used all around the library
1945 to create different types of objects, thus generalizing the `std::make_xxx`
1946 family of functions. For example, one can create a `hana::range` of
1947 compile-time integers with `make<range_tag>`:
1948
1949 @snippet example/tutorial/containers.cpp make<range_tag>
1950
1951 > These types with a trailing `_tag` are dummy types __representing__ a family
1952 > of heterogeneous containers (`hana::tuple`, `hana::map`, etc..). Tags are
1953 > documented in the section on [Hana's core](@ref tutorial-core-tags).
1954
1955 For convenience, whenever a component of Hana provides a `make<xxx_tag>`
1956 function, it also provides the `make_xxx` shortcut to reduce typing. Also, an
1957 interesting point that can be raised in this example is the fact that `r` is
1958 `constexpr`. In general, whenever a container is initialized with constant
1959 expressions only (which is the case for `r`), that container may be marked
1960 as `constexpr`.
1961
1962 So far, we have only created containers with the `make_xxx` family of
1963 functions. However, some containers do provide constructors as part of
1964 their interface. For example, one can create a `hana::tuple` just like
1965 one would create a `std::tuple`:
1966
1967 @snippet example/tutorial/containers.cpp tuple_constructor
1968
1969 When constructors (or any member function really) are part of the public
1970 interface, they will be documented on a per-container basis. However,
1971 in the general case, one should not take for granted that a container
1972 can be constructed as the tuple was constructed above. For example,
1973 trying to create a `hana::range` that way will __not__ work:
1974
1975 @code{.cpp}
1976 hana::range<???> xs{hana::int_c<3>, hana::int_c<10>};
1977 @endcode
1978
1979 In fact, we can't even specify the type of the object we'd like to create in
1980 that case, because the exact type of a `hana::range` is implementation-defined,
1981 which brings us to the next section.
1982
1983
1984 @subsection tutorial-containers-types Container types
1985
1986 The goal of this section is to clarify what can be expected from the types of
1987 Hana's containers. Indeed, so far, we always let the compiler deduce the
1988 actual type of containers by using the `make_xxx` family of functions along
1989 with `auto`. But in general, what can we say about the type of a container?
1990
1991 @snippet example/tutorial/containers.cpp types
1992
1993 The answer is that it depends. Some containers have well defined types, while
1994 others do not specify their representation. In this example, the type of the
1995 object returned by `make_tuple` is well-defined, while the type returned by
1996 `make_range` is implementation-defined:
1997
1998 @snippet example/tutorial/containers.cpp types_maximally_specified
1999
2000 This is documented on a per-container basis; when a container has an
2001 implementation-defined representation, a note explaining exactly what
2002 can be expected from that representation is included in the container's
2003 description. There are several reasons for leaving the representation of
2004 a container unspecified; they are explained in the
2005 [rationales](@ref tutorial-rationales-container_representation).
2006 When the representation of a container is implementation-defined, one must
2007 be careful not to make any assumptions about it, unless those assumption
2008 are explicitly allowed in the documentation of the container.
2009
2010
2011 @subsubsection tutorial-containers-types-overloading Overloading on container types
2012
2013 While necessary, leaving the type of some containers unspecified makes some
2014 things very difficult to achieve, like overloading functions on heterogeneous
2015 containers:
2016
2017 @code{cpp}
2018 template <typename T>
2019 void f(std::vector<T> xs) {
2020   // ...
2021 }
2022
2023 template <typename ...???>
2024 void f(unspecified-range-type<???> r) {
2025   // ...
2026 }
2027 @endcode
2028
2029 The `is_a` utility is provided for this reason (and others). `is_a` allows
2030 checking whether a type is a precise kind of container using its tag,
2031 regardless of the actual type of the container. For example, the above
2032 example could be rewritten as
2033
2034 @snippet example/tutorial/containers.cpp overloading
2035
2036 This way, the second overload of `f` will only match when `R` is a type whose
2037 tag is `range_tag`, regardless of the exact representation of that range. Of
2038 course, `is_a` can be used with any kind of container: `tuple`, `map`, `set`
2039 and so on.
2040
2041
2042 @subsection tutorial-containers-elements Container elements
2043
2044 In Hana, containers own their elements. When a container is created, it makes
2045 a _copy_ of the elements used to initialize it and stores them inside the
2046 container. Of course, unnecessary copies are avoided by using move semantics.
2047 Because of those owning semantics, the lifetime of the objects inside the
2048 container is the same as that of the container.
2049
2050 @snippet example/tutorial/containers.cpp lifetime
2051
2052 Much like containers in the standard library, containers in Hana expect their
2053 elements to be objects. For this reason, references _may not_ be stored in
2054 them. When references must be stored inside a container, one should use a
2055 `std::reference_wrapper` instead:
2056
2057 @snippet example/tutorial/containers.cpp reference_wrapper
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068 @section tutorial-algorithms Generalities on algorithms
2069
2070 ------------------------------------------------------------------------------
2071 Much like the previous section introduced general but important notions about
2072 heterogeneous containers, this section introduces general notions about
2073 heterogeneous algorithms.
2074
2075
2076 @subsection tutorial-algorithms-value By-value semantics
2077
2078 Algorithms in Hana always return a new container holding the result. This
2079 allows one to easily chain algorithms by simply using the result of the first
2080 as the input of the second. For example, to apply a function to every element
2081 of a tuple and then reverse the result, one simply has to connect the `reverse`
2082 and `transform` algorithms:
2083
2084 @snippet example/tutorial/algorithms.cpp reverse_transform
2085
2086 This is different from the algorithms of the standard library, where one has
2087 to provide iterators to the underlying sequence. For reasons documented in the
2088 [rationales](@ref tutorial-rationales-iterators), an iterator-based design was
2089 considered but was quickly dismissed in favor of composable and efficient
2090 abstractions better suited to the very particular context of heterogeneous
2091 programming.
2092
2093 One might also think that returning full sequences that own their elements
2094 from an algorithm would lead to tons of undesirable copies. For example, when
2095 using `reverse` and `transform`, one could think that an intermediate copy is
2096 made after the call to `transform`:
2097
2098 @snippet example/tutorial/algorithms.cpp reverse_transform_copy
2099
2100 To make sure this does not happen, Hana uses perfect forwarding and move
2101 semantics heavily so it can provide an almost optimal runtime performance.
2102 So instead of doing a copy, a move occurs between `reverse` and `transform`:
2103
2104 @snippet example/tutorial/algorithms.cpp reverse_transform_move
2105
2106 Ultimately, the goal is that code written using Hana should be equivalent to
2107 clever hand-written code, except it should be enjoyable to write. Performance
2108 considerations are explained in depth in their own [section]
2109 (@ref tutorial-performance).
2110
2111
2112 @subsection tutorial-algorithms-laziness (Non-)Laziness
2113
2114 Algorithms in Hana are not lazy. When an algorithm is called, it does its
2115 job and returns a new sequence containing the result, end of the story.
2116 For example, calling the `permutations` algorithm on a large sequence is
2117 a stupid idea, because Hana will actually compute all the permutations:
2118
2119 @code{cpp}
2120     auto perms = hana::permutations(hana::make_tuple(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
2121     // perms has 3 628 800 elements, and your compiler just crashed
2122 @endcode
2123
2124 To contrast, algorithms in Boost.Fusion return views which hold the original
2125 sequence by reference and apply the algorithm on demand, as the elements of
2126 the sequence are accessed. This leads to subtle lifetime issues, like having
2127 a view that refers to a sequence that was destroyed. Hana's design assumes
2128 that most of the time, we want to access all or almost all the elements in a
2129 sequence anyway, and hence performance is not a big argument in favor of
2130 laziness.
2131
2132
2133 @subsection tutorial-algorithms-codegen What is generated?
2134
2135 Algorithms in Hana are a bit special with respect to the runtime code they are
2136 expanded into. The goal of this subsection is not to explain exactly what code
2137 is generated, which depends on the compiler anyway, but to give a feel for
2138 things. Basically, a Hana algorithm is like an unrolled version of an
2139 equivalent classical algorithm. Indeed, since the bounds of the processed
2140 sequence are known at compile-time, it makes sense that we can unroll the
2141 loop over the sequence. For example, let's consider the `for_each` algorithm:
2142
2143 @code{cpp}
2144 auto xs = hana::make_tuple(0, 1, 2, 3);
2145 hana::for_each(xs, f);
2146 @endcode
2147
2148 If `xs` was a runtime sequence instead of a tuple, its length would only be
2149 known at runtime and the above code would have to be implemented as a loop:
2150
2151 @code{cpp}
2152 for (int i = 0; i < xs.size(); ++i) {
2153   f(xs[i]);
2154 }
2155 @endcode
2156
2157 However, in our case, the length of the sequence is known at compile-time and
2158 so we don't have to check the index at each iteration. Hence, we can just
2159 write:
2160
2161 @code{cpp}
2162 f(xs[0_c]);
2163 f(xs[1_c]);
2164 f(xs[2_c]);
2165 f(xs[3_c]);
2166 @endcode
2167
2168 The main difference here is that no bound checking and index increment is done
2169 at each step, because there is no index anymore; the loop was effectively
2170 unrolled. In some cases, this can be desirable for performance reasons. In
2171 other cases, this can be detrimental to performance because it causes the
2172 code size to grow. As always, performance is a tricky subject and whether
2173 you actually want loop unrolling to happen should be tackled on a case-by-case
2174 basis. As a rule of thumb, algorithms processing all (or a subset) of the
2175 elements of a container are unrolled. In fact, if you think about it, this
2176 unrolling is the only way to go for heterogeneous sequences, because different
2177 elements of the sequence may have different types. As you might have noticed,
2178 we're not using normal indices into the tuple, but compile-time indices, which
2179 can't be generated by a normal `for` loop. In other words, the following does
2180 not make sense:
2181
2182 @code{cpp}
2183 for (??? i = 0_c; i < xs.size(); ++i) {
2184   f(xs[i]);
2185 }
2186 @endcode
2187
2188
2189 @subsection tutorial-algorithms-effects Side effects and purity
2190
2191 By default, Hana assumes functions to be pure. A pure function is a function
2192 that has no side-effects at all. In other words, it is a function whose effect
2193 on the program is solely determined by its return value. In particular, such a
2194 function may not access any state that outlives a single invocation of the
2195 function. These functions have very nice properties, like the ability to
2196 reason mathematically about them, to reorder or even eliminate calls, and
2197 so on. Except where specified otherwise, all functions used with Hana (i.e.
2198 used in higher order algorithms) should be pure. In particular, functions
2199 passed to higher order algorithms are not guaranteed to be called any
2200 specific number of times. Furthermore, the order of execution is generally
2201 not specified and should therefore not be taken for granted. If this lack of
2202 guarantees about function invocations seems crazy, consider the following use
2203 of the `any_of` algorithm:
2204
2205 @snippet example/tutorial/algorithms.cpp effects
2206
2207 @note
2208 For this to work, the external adapters for `std::integral_constant` contained
2209 in `<boost/hana/ext/std/integral_constant.hpp>` must be included.
2210
2211 According to the previous section on unrolling, this algorithm should be
2212 expanded into something like:
2213
2214 @code{cpp}
2215 auto xs = hana::make_tuple("hello"s, 1.2, 3);
2216 auto pred = [](auto x) { return std::is_integral<decltype(x)>{}; };
2217
2218 auto r = hana::bool_c<
2219   pred(xs[0_c]) ? true :
2220   pred(xs[1_c]) ? true :
2221   pred(xs[2_c]) ? true :
2222   false
2223 >;
2224
2225 BOOST_HANA_CONSTANT_CHECK(r);
2226 @endcode
2227
2228 Of course, the above code can't work as-is, because we're calling `pred` inside
2229 something that would have to be a constant expression, but `pred` is a lambda
2230 (and lambdas can't be called in constant expressions). However, whether any of
2231 these objects has an integral type is clearly known at compile-time, and hence
2232 we would expect that computing the answer only involves compile-time
2233 computations. In fact, this is exactly what Hana does, and the above
2234 algorithm is expanded into something like:
2235
2236 @snippet example/tutorial/algorithms.cpp effects.codegen
2237
2238 @note
2239 As you will be able to deduce from the next section on cross-phase computations,
2240 the implementation of `any_of` must actually be more general than this. However,
2241 this [lie-to-children][] is perfect for educational purposes.
2242
2243 As you can see, the predicate is never even executed; only its result type on
2244 a particular object is used. Regarding the order of evaluation, consider the
2245 `transform` algorithm, which is specified (for tuples) as:
2246
2247 @code{cpp}
2248 hana::transform(hana::make_tuple(x1, ..., xn), f) == hana::make_tuple(f(x1), ..., f(xn))
2249 @endcode
2250
2251 Since `make_tuple` is a function, and since the evaluation order for the
2252 arguments of a function is unspecified, the order in which `f` is called
2253 on each element of the tuple is unspecified too. If one sticks to pure
2254 functions, everything works fine and the resulting code is often easier
2255 to understand. However, some exceptional algorithms like `for_each` do
2256 expect impure functions, and they guarantee an order of evaluation. Indeed,
2257 a `for_each` algorithm that would only take pure functions would be pretty
2258 much useless. When an algorithm can accept an impure function or guarantees
2259 some order of evaluation, the documentation for that algorithm will mention
2260 it explicitly. However, by default, no guarantees may be taken for granted.
2261
2262
2263 @subsection tutorial-algorithms-cross_phase Cross-phase algorithms
2264
2265 This section introduces the notion of cross-phase computations and algorithms.
2266 In fact, we have already used cross-phase algorithms in the [quick start]
2267 (@ref tutorial-quickstart), for example with `filter`, but we did not explain
2268 exactly what was happening at that time. But before we introduce cross-phase
2269 algorithms, let's define what we mean by _cross-phase_. The phases we're
2270 referring to here are the compilation and the execution of a program. In C++
2271 as in most statically typed languages, there is a clear distinction between
2272 compile-time and runtime; this is called phase distinction. When we speak of
2273 a cross-phase computation, we mean a computation that is somehow performed
2274 across those phases; i.e. that is partly executed at compile-time and partly
2275 executed at runtime.
2276
2277 Like we saw in earlier examples, some functions are able to return something
2278 that can be used at compile-time even when they are called on a runtime value.
2279 For example, let's consider the `length` function applied to a non-`constexpr`
2280 container:
2281
2282 @snippet example/tutorial/algorithms.cpp cross_phase.setup
2283
2284 Obviously, the tuple can't be made `constexpr`, since it contains runtime
2285 `std::string`s. Still, even though it is not called on a constant expression,
2286 `length` returns something that can be used at compile-time. If you think of
2287 it, the size of the tuple is known at compile-time regardless of its content,
2288 and hence it would only make sense for this information to be available to us
2289 at compile-time. If that seems surprising, think about `std::tuple` and
2290 `std::tuple_size`:
2291
2292 @snippet example/tutorial/algorithms.cpp cross_phase.std::tuple_size
2293
2294 Since the size of the tuple is encoded in its type, it is always available
2295 at compile-time regardless of whether the tuple is `constexpr` or not. In Hana,
2296 this is implemented by having `length` return an `IntegralConstant`. Since an
2297 `IntegralConstant`'s value is encoded in its type, the result of `length` is
2298 contained in the type of the object it returns, and the length is therefore
2299 known at compile-time. Because `length` goes from a runtime value (the
2300 container) to a compile-time value (the `IntegralConstant`), `length` is a
2301 trivial example of a cross-phase algorithm (trivial because it does not really
2302 manipulate the tuple). Another algorithm that is very similar to `length` is
2303 the `is_empty` algorithm, which returns whether a container is empty:
2304
2305 @snippet example/tutorial/algorithms.cpp cross_phase.is_empty
2306
2307 More generally, any algorithm that takes a container whose value is known at
2308 runtime but queries something that can be known at compile-time should be able
2309 to return an `IntegralConstant` or another similar compile-time value. Let's
2310 make things slightly more complicated by considering the `any_of` algorithm,
2311 which we already encountered in the previous section:
2312
2313 @snippet example/tutorial/algorithms.cpp cross_phase.any_of_runtime
2314
2315 In this example, the result can't be known at compile-time, because the
2316 predicate returns a `bool` that is the result of comparing two `std::string`s.
2317 Since `std::string`s can't be compared at compile-time, the predicate must
2318 operate at runtime, and the overall result of the algorithm can then only be
2319 known at runtime too. However, let's say we used `any_of` with the following
2320 predicate instead:
2321
2322 @snippet example/tutorial/algorithms.cpp cross_phase.any_of_compile_time
2323
2324 @note
2325 For this to work, the external adapters for `std::integral_constant` contained
2326 in `<boost/hana/ext/std/integral_constant.hpp>` must be included.
2327
2328 First, since the predicate is only querying information about the type of each
2329 element of the tuple, it is clear that its result can be known at compile-time.
2330 Since the number of elements in the tuple is also known at compile-time, the
2331 overall result of the algorithm can, in theory, be known at compile-time. More
2332 precisely, what happens is that the predicate returns a value initialized
2333 `std::is_same<...>`, which inherits from `std::integral_constant`. Hana
2334 recognizes these objects, and the algorithm is written in such a way that it
2335 preserves the `compile-time`ness of the predicate's result. In the end,
2336 `any_of` hence returns an `IntegralConstant` holding the result of the
2337 algorithm, and we use the compiler's type deduction in a clever way to make
2338 it look easy. Hence, it would be equivalent to write (but then you would need
2339 to already know the result of the algorithm!):
2340
2341 @snippet example/tutorial/algorithms.cpp cross_phase.any_of_explicit
2342
2343 Ok, so some algorithms are able to return compile-time values when their input
2344 satisfies some constraints with respect to `compile-time`ness. However, other
2345 algorithms are more restrictive and they _require_ their inputs to satisfy some
2346 constraints regarding `compile-time`ness, without which they are not able to
2347 operate at all. An example of this is `filter`, which takes a sequence and a
2348 predicate, and returns a new sequence containing only those elements for which
2349 the predicate is satisfied. `filter` requires the predicate to return an
2350 `IntegralConstant`. While this requirement may seem stringent, it really makes
2351 sense if you think about it. Indeed, since we're removing some elements from
2352 the heterogeneous sequence, the type of the resulting sequence depends on the
2353 result of the predicate. Hence, the result of the predicate has to be known at
2354 compile-time for the compiler to be able to assign a type to the returned
2355 sequence. For example, consider what happens when we try to filter a
2356 heterogeneous sequence as follows:
2357
2358 @code{cpp}
2359 auto animals = hana::make_tuple(Fish{"Nemo"}, Cat{"Garfield"}, Dog{"Snoopy"});
2360
2361 auto no_garfield = hana::filter(animals, [](auto animal) {
2362   return animal.name != "Garfield"s;
2363 });
2364 @endcode
2365
2366 Clearly, we know that the predicate will only return false on the second
2367 element, and hence the result _should be_ a `[Fish, Dog]` tuple. However,
2368 the compiler has no way of knowing this since the predicate's result is the
2369 result of a runtime computation, which happens way after the compiler has
2370 finished its job. Hence, the compiler does not have enough information to
2371 determine the return type of the algorithm. However, we could `filter` the
2372 same sequence with any predicate whose result is available at compile-time:
2373
2374 @snippet example/tutorial/algorithms.cpp cross_phase.filter
2375
2376 Since the predicate returns an `IntegralConstant`, we know which elements
2377 of the heterogeneous sequence we'll be keeping at compile-time. Hence, the
2378 compiler is able to figure out the return type of the algorithm. Other
2379 algorithms like `partition` and `sort` work similarly; special algorithm
2380 requirements are always documented, just read the reference documentation
2381 of an algorithm before using it to avoid surprises.
2382
2383 This is the end of the section on algorithms. While this constitutes a fairly
2384 complete explanation of phase interaction inside algorithms, a deeper
2385 understanding can be gained by reading the [advanced section]
2386 (@ref tutorial-appendix-constexpr) on `constexpr` and the reference
2387 for `Constant` and `IntegralConstant`.
2388
2389
2390 @warning
2391 Hana's algorithms are `constexpr` function objects instead of being template
2392 functions. This allows passing them to higher-order algorithms, which is very
2393 useful. However, since those function objects are defined at namespace scope
2394 in the header files, this causes each translation unit to see a different
2395 algorithm object. Hence, the address of an algorithm function object is not
2396 guaranteed to be unique across translation units, which can cause an ODR
2397 violation if one relies on such an address. So, in short, do not rely on the
2398 uniqueness of the address of any global object provided by Hana, which does
2399 not make sense in the general case anyway because such objects are `constexpr`.
2400 See [issue #76](https://github.com/boostorg/hana/issues/76) for more information.
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411 @section tutorial-performance Performance considerations
2412
2413 ------------------------------------------------------------------------------
2414 C++ programmers love performance, so here's a whole section dedicated to it.
2415 Since Hana lives on the frontier between runtime and compile-time computations,
2416 we are not only interested in runtime performance, but also compile-time
2417 performance. Since both topics are pretty much disjoint, we treat them
2418 separately below.
2419
2420 @note
2421 The benchmarks presented in this section are updated automatically when we
2422 push to the repository. If you notice results that do not withstand the
2423 claims made here, open a [GitHub issue][Hana.issues]; it could be a
2424 performance regression.
2425
2426 @warning
2427 As of writing this, not all of Hana's containers are optimized. Implementing
2428 Hana was a big enough challenge that containers were initially written naively
2429 and are now in the process of being rigorously optimized. In particular, the
2430 associative containers (`hana::map` and `hana::set`) have a pretty bad
2431 compile-time behavior because of their naive implementation, and their runtime
2432 behavior also seems to be problematic in some cases. Improving this situation
2433 is in the TODO list.
2434
2435
2436 @subsection tutorial-performance-compile Compile-time performance
2437
2438 C++ metaprogramming brings its share of awful things. One of the most annoying
2439 and well-known problem associated to it is interminable compilation times.
2440 Hana claims to be more compile-time efficient than its predecessors; this is
2441 a bold claim and we will now try to back it. Of course, Hana can't do miracles;
2442 metaprogramming is a byproduct of the C++ template system and the compiler is
2443 not meant to be used as an interpreter for some meta language. However, by
2444 using cutting edge and intensely benchmarked techniques, Hana is able to
2445 minimize the strain on the compiler.
2446
2447 @note
2448 While Hana has better compile-times than pre-C++11 metaprogramming libraries,
2449 modern libraries supporting only type-level computations (such as [Brigand][])
2450 can provide better compile-times, at the cost of generality. Indeed, Hana's
2451 ability to manipulate runtime values comes at a compile-time cost, no matter
2452 how hard we try to mitigate it. If you want to use Hana for intensive type-level
2453 computations, you should benchmark and see whether it suits you.
2454
2455 Before we dive, let me make a quick note on the methodology used to measure
2456 compile-time performance in Hana. Previous metaprogramming libraries measured
2457 the compile-time complexity of their meta-algorithms and meta-sequences by
2458 looking at the number of instantiations the compiler had to perform. While
2459 easy to understand, this way of measuring the compile-time complexity actually
2460 does not give us a lot of information regarding the compilation time, which
2461 is what we're interested in minimizing at the end of the day. Basically, the
2462 reason for this is that template metaprogramming is such a twisted model of
2463 computation that it's very hard to find a standard way of measuring the
2464 performance of algorithms. Hence, instead of presenting meaningless complexity
2465 analyses, we prefer to benchmark everything on every supported compiler and to
2466 pick the best implementation on that compiler. Also note that the benchmarks
2467 we present here are quite precise. Indeed, even though we do not take multiple
2468 measurements and take their mean or something similar to reduce incertitude,
2469 the benchmarks are very stable when they are regenerated, which suggests a
2470 reasonably good precision. Now, let's dive.
2471
2472 First, Hana minimizes its dependency on the preprocessor. In addition to
2473 yielding cleaner error messages in many cases, this reduces the overall
2474 parsing and preprocessing time for header files. Also, because Hana only
2475 supports cutting edge compilers, there are very few workarounds in the
2476 library, which results in a cleaner and smaller library. Finally, Hana
2477 minimizes reliance on any kind of external dependencies. In particular,
2478 it only uses other Boost libraries in a few specific cases, and it does
2479 not rely on the standard library for the largest part. There are several
2480 reasons (other than include times) for doing so; they are documented in
2481 the [rationales](@ref tutorial-rationales-dependencies).
2482
2483 Below is a chart showing the time required to include different libraries. The
2484 chart shows the time for including everything in the (non-external) public API
2485 of each library. For example, for Hana this means the `<boost/hana.hpp>` header,
2486 which excludes the external adapters. For other libraries like Boost.Fusion,
2487 this means including all the public headers in the `boost/fusion/` directory,
2488 but not the adapters for external libraries like the MPL.
2489
2490 <div class="benchmark-chart"
2491      style="min-width: 310px; height: 400px; margin: 0 auto"
2492      data-dataset="benchmark.including.compile.json">
2493 </div>
2494
2495 In addition to reduced preprocessing times, Hana uses modern techniques to
2496 implement heterogeneous sequences and algorithms in the most compile-time
2497 efficient way possible. Before jumping to the compile-time performance of
2498 the algorithms, we will have a look at the compile-time cost of creating
2499 heterogeneous sequences. Indeed, since we will be presenting algorithms that
2500 work on sequences, we must be aware of the cost of creating the sequences
2501 themselves, since that will influence the benchmarks for the algorithms.
2502 The following chart presents the compile-time cost of creating a sequence
2503 of `n` heterogeneous elements.
2504
2505 <div class="benchmark-chart"
2506      style="min-width: 310px; height: 400px; margin: 0 auto"
2507      data-dataset="benchmark.make.compile.json">
2508 </div>
2509
2510 @note
2511 You can zoom on the chart by selecting an area to zoom into. Also, you can
2512 hide a series of points by clicking on it in the legend on the right.
2513
2514 The benchmark methodology is to always create the sequences in the most
2515 efficient way possible. For Hana and `std::tuple`, this simply means using
2516 the appropriate `make_tuple` function. However, for the MPL, this means
2517 creating a `mpl::vectorN` of size up to 20, and then using `mpl::push_back`
2518 to create larger vectors. We use a similar technique for Fusion sequences.
2519 The reason for doing so is that Fusion and MPL sequences have fixed size
2520 limits, and the techniques used here have been found to be the fastest way
2521 to create longer sequences.
2522
2523 For completeness, we also present the compile-time cost of creating a
2524 `std::array` with `n` elements. However, note that `std::array` can only
2525 hold elements with a single type, so we're comparing apples and oranges
2526 here. As you can see, the cost of creating a `std::array` is constant and
2527 essentially inexistent (the non-zero overhead is that of simply including
2528 the `<array>` header). Hence, while Hana provides improved compile-times
2529 over other heterogeneous containers, please stick with normal homogeneous
2530 containers if that's all you need for your application; your compile-times
2531 will be much faster that way.
2532
2533 You can also see that creating sequences has a non-negligible cost. Actually,
2534 this is really the most expensive part of doing heterogeneous computations,
2535 as you will see in the following charts. Hence, when you look at the charts
2536 below, keep in mind the cost of merely creating the sequences. Also note that
2537 only the most important algorithms will be presented here, but the [Metabench][]
2538 project provides micro benchmarks for compile-time performance for almost all
2539 of Hana's algorithms. Also, the benchmarks we present compare several different
2540 libraries. However, since Hana and Fusion can work with values and not only
2541 types, comparing their algorithms with type-only libraries like MPL is not
2542 really fair. Indeed, Hana and Fusion algorithms are more powerful since they
2543 also allow runtime effects to be performed. However, the comparison between
2544 Fusion and Hana is fair, because both libraries are just as powerful (strictly
2545 speaking). Finally, we can't show benchmarks of the algorithms for `std::tuple`,
2546 because the standard does not provide equivalent algorithms. Of course, we
2547 could use Hana's external adapters, but that would not be a faithful comparison.
2548
2549 The first algorithm which is ubiquitous in metaprogramming is `transform`.
2550 It takes a sequence and a function, and returns a new sequence containing the
2551 result of applying the function to each element. The following chart presents
2552 the compile-time performance of applying `transform` to a sequence of `n`
2553 elements. The `x` axis represents the number of elements in the sequence, and
2554 the `y` axis represents the compilation time in seconds. Also note that we're
2555 using the `transform` equivalent in each library; we're not using Hana's
2556 `transform` through the Boost.Fusion adapters, for example, because we really
2557 want to benchmark their implementation against ours.
2558
2559 <div class="benchmark-chart"
2560      style="min-width: 310px; height: 400px; margin: 0 auto"
2561      data-dataset="benchmark.transform.compile.json">
2562 </div>
2563
2564 Here, we can see that Hana's tuple performs better than all the other
2565 alternatives. This is mainly due to the fact that we use C++11 variadic
2566 parameter pack expansion to implement this algorithm under the hood, which
2567 is quite efficient.
2568
2569 Before we move on, it is important to mention something regarding the benchmark
2570 methodology for Fusion algorithms. Some algorithms in Fusion are lazy, which
2571 means that they don't actually perform anything, but simply return a modified
2572 view to the original data. This is the case of `fusion::transform`, which
2573 simply returns a transformed view that applies the function to each element
2574 of the original sequence as those elements are accessed. If we want to
2575 benchmark anything at all, we need to force the evaluation of that view, as
2576 would eventually happen when accessing the elements of the sequence in real
2577 code. However, for complex computations with multiple layers, a lazy approach
2578 may yield a substantially different compile-time profile. Of course, this
2579 difference is poorly represented in micro benchmarks, so keep in mind that
2580 these benchmarks only give a part of the big picture. For completeness in the
2581 rest of the section, we will mention when a Fusion algorithm is lazy, so that
2582 you know when we're _artificially_ forcing the evaluation of the algorithm for
2583 the purpose of benchmarking.
2584
2585 @note
2586 We are currently considering adding lazy views to Hana. If this feature is
2587 important to you, please let us know by commenting
2588 [this issue](https://github.com/boostorg/hana/issues/193).
2589
2590 The second important class of algorithms are folds. Folds can be used to
2591 implement many other algorithms like `count_if`, `minimum` and so on.
2592 Hence, a good compile-time performance for fold algorithms ensures a good
2593 compile-time performance for those derived algorithms, which is why we're
2594 only presenting folds here. Also note that all the non-monadic fold variants
2595 are somewhat equivalent in terms of compile-time, so we only present the left
2596 folds. The following chart presents the compile-time performance of applying
2597 `fold_left` to a sequence of `n` elements. The `x` axis represents the number
2598 of elements in the sequence, and the `y` axis represents the compilation time
2599 in seconds. The function used for folding is a dummy function that does nothing.
2600 In real code, you would likely fold with a nontrivial operation, so the curves
2601 would be worse than that. However, these are micro benchmarks and hence they
2602 only show the performance of the algorithm itself.
2603
2604 <div class="benchmark-chart"
2605      style="min-width: 310px; height: 400px; margin: 0 auto"
2606      data-dataset="benchmark.fold_left.compile.json">
2607 </div>
2608
2609 The third and last algorithm that we present here is the `find_if` algorithm.
2610 This algorithm is difficult to implement efficiently, because it requires
2611 stopping at the first element which satisfies the given predicate. For the
2612 same reason, modern techniques don't really help us here, so this algorithm
2613 constitutes a good test of the implementation quality of Hana, without taking
2614 into account the free lunch given to use by C++14.
2615
2616 <div class="benchmark-chart"
2617      style="min-width: 310px; height: 400px; margin: 0 auto"
2618      data-dataset="benchmark.find_if.compile.json">
2619 </div>
2620
2621 As you can see, Hana performs better than Fusion, and as well as MPL, yet
2622 Hana's `find_if` can be used with values too, unlike MPL's. This concludes
2623 the section on compile-time performance. In case you want to see the
2624 performance of an algorithm that we have not presented here, the [Metabench][]
2625 project provides compile-time benchmarks for most of Hana's algorithms.
2626
2627
2628 @subsection tutorial-performance-runtime Runtime performance
2629
2630 Hana was designed to be very efficient at runtime. But before we dive into the
2631 details, let's clarify one thing. Hana being a metaprogramming library which
2632 allows manipulating both types and values, it does not always make sense to
2633 even talk about runtime performance. Indeed, for type-level computations and
2634 computations on `IntegralConstant`s, runtime performance is simply not a
2635 concern, because the result of the computation is contained in a _type_, which
2636 is a purely compile-time entity. In other words, these computations involve
2637 only compile-time work, and no code is even generated to perform these
2638 computations at runtime. The only case where it makes sense to discuss runtime
2639 performance is when manipulating runtime values in heterogeneous containers
2640 and algorithms, because this is the only case where the compiler has to
2641 generate some runtime code. It is therefore only computations of this sort
2642 that we will be studying in the remainder of this section.
2643
2644 Like we did for compile-time benchmarks, the methodology used to measure
2645 runtime performance in Hana is data driven rather than analytical. In other
2646 words, instead of trying to determine the complexity of an algorithm by
2647 counting the number of basic operations it does as a function of the input
2648 size, we simply take measurements for the most interesting cases and see how
2649 it behaves. There are a couple of reasons for doing so. First, we do not
2650 expect Hana's algorithms to be called on large inputs since those algorithms
2651 work on heterogeneous sequences whose length must be known at compile-time.
2652 For example, if you tried to call the `find_if` algorithm on a sequence of
2653 100k elements, your compiler would simply die while trying to generate the
2654 code for this algorithm. Hence, algorithms can't be called on very large inputs
2655 and the analytical approach then loses a lot of its attractiveness. Secondly,
2656 processors have evolved into pretty complex beasts, and the actual performance
2657 you'll be able to squeeze out is actually controlled by much more than the
2658 mere number of steps your algorithm is doing. For example, bad cache behavior
2659 or branch misprediction could turn a theoretically efficient algorithm into a
2660 slowpoke, especially for small inputs. Since Hana causes a lot of unrolling to
2661 happen, these factors must be considered even more carefully and any analytical
2662 approach would probably only comfort us into thinking we're efficient. Instead,
2663 we want hard data, and pretty charts to display it!
2664
2665 @note
2666 Like for compile-time performance, we're forcing the evaluation of some Fusion
2667 algorithms that are normally lazy. Again, depending on the complexity of the
2668 computation, a lazy algorithm may cause substantially different code to be
2669 generated or a different design to be used, for better or worse. Keep this
2670 in mind when you look at these runtime benchmarks. If performance is absolutely
2671 critical to your application, you should profile _before_ and _after_ switching
2672 from Fusion to Hana. And let us know if Hana performs worse; we'll fix it!
2673
2674 There are a couple of different aspects we will want to benchmark. First, we
2675 will obviously want to benchmark the execution time of the algorithms.
2676 Secondly, because of the by-value semantics used throughout the library, we
2677 will also want to make sure that the minimum amount of data is copied around.
2678 Finally, we will want to make sure that using Hana does not cause too much
2679 code bloat because of unrolling, as explained in the [section]
2680 (@ref tutorial-algorithms-codegen) on algorithms.
2681
2682 Just like we studied only a couple of key algorithms for compile-time
2683 performance, we will focus on the runtime performance of a few algorithms.
2684 For each benchmarked aspect, we will compare the algorithm as implemented by
2685 different libraries. Our goal is to always be at least as efficient as
2686 Boost.Fusion, which is near from optimality in terms of runtime performance.
2687 For comparison, we also show the same algorithm as executed on a runtime
2688 sequence, and on a sequence whose length is known at compile-time but whose
2689 `transform` algorithm does not use explicit loop unrolling. All the benchmarks
2690 presented here are done in a _Release_ CMake configuration, which takes care
2691 of passing the proper optimization flags (usually `-O3`). Let's start with the
2692 following chart, which shows the execution time required to `transform`
2693 different kinds of sequences:
2694
2695 <div class="benchmark-chart"
2696      style="min-width: 310px; height: 400px; margin: 0 auto"
2697      data-dataset="benchmark.transform.execute.json">
2698 </div>
2699
2700 @note
2701 Keep in mind that `fusion::transform` is usually lazy, and we're forcing its
2702 evaluation for the purpose of benchmarking.
2703
2704 As you can see, Hana and Fusion are pretty much on the same line. `std::array`
2705 is slightly slower for larger collections data sets, and `std::vector` is
2706 noticeably slower for larger collections. Since we also want to look out for
2707 code bloat, let's take a look at the size of the executable generated for the
2708 exact same scenario:
2709
2710 <div class="benchmark-chart"
2711      style="min-width: 310px; height: 400px; margin: 0 auto"
2712      data-dataset="benchmark.transform.bloat.json">
2713 </div>
2714
2715 As you can see, code bloat does not seem to be an issue, at least not one that
2716 can be detected in micro benchmarks such as this one. Let's now take a look at
2717 the `fold` algorithm, which is used very frequently:
2718
2719 <div class="benchmark-chart"
2720      style="min-width: 310px; height: 400px; margin: 0 auto"
2721      data-dataset="benchmark.fold_left.execute.json">
2722 </div>
2723
2724 Here, you can see that everybody is performing pretty much the same, which
2725 is a good sign that Hana is at least not screwing things up.
2726 Again, let's look at the executable size:
2727
2728 <div class="benchmark-chart"
2729      style="min-width: 310px; height: 400px; margin: 0 auto"
2730      data-dataset="benchmark.fold_left.bloat.json">
2731 </div>
2732
2733 Here again, the code size did not explode. So at least for moderate usages of
2734 Hana (and Fusion for that matter, since they have the same problem), code
2735 bloat should not be a major concern. The containers in the charts we just
2736 presented contain randomly generated `int`s, which is cheap to copy around and
2737 lends itself well to micro benchmarks. However, what happens when we chain
2738 multiple algorithms on a container whose elements are expensive to copy? More
2739 generally, the question is: when an algorithm is passed a temporary object,
2740 does it seize the opportunity to avoid unnecessary copies? Consider:
2741
2742 @code{cpp}
2743 auto xs = hana::make_tuple("some"s, "huge"s, "string"s);
2744
2745 // No copy of xs's elements should be made: they should only be moved around.
2746 auto ys = hana::reverse(std::move(xs));
2747 @endcode
2748
2749 To answer this question, we'll look at the chart generated when benchmarking
2750 the above code for strings of about 1k characters. However, note that it does
2751 not really make sense to benchmark this for standard library algorithms,
2752 because they do not return containers.
2753
2754 <div class="benchmark-chart"
2755      style="min-width: 310px; height: 400px; margin: 0 auto"
2756      data-dataset="benchmark.reverse.move.json">
2757 </div>
2758
2759 @note
2760 Keep in mind that `fusion::reverse` is usually lazy, and we're forcing its
2761 evaluation for the purpose of benchmarking.
2762
2763 As you can see, Hana is faster than Fusion, probably because of a more
2764 consistent use of move semantics in the implementation. If we had not
2765 provided a temporary container to `reverse`, no move could have been
2766 performed by Hana and both libraries would have performed similarly:
2767
2768 <div class="benchmark-chart"
2769      style="min-width: 310px; height: 400px; margin: 0 auto"
2770      data-dataset="benchmark.reverse.nomove.json">
2771 </div>
2772
2773 This concludes the section on runtime performance. Hopefully you are now
2774 convinced that Hana was built for speed. Performance is important to us:
2775 if you ever encounter a scenario where Hana causes bad code to be generated
2776 (and the fault is not on the compiler), please open an [issue][Hana.issues]
2777 so the problem can be addressed.
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788 @section tutorial-ext Integration with external libraries
2789
2790 ------------------------------------------------------------------------------
2791
2792 Hana provides out-of-the-box integration with some existing libraries.
2793 Specifically, this means that you can use some containers from these
2794 libraries in Hana's algorithms by simply including the appropriate header
2795 making the bridge between Hana and the external component. This can be
2796 very useful for porting existing code from e.g. Fusion/MPL to Hana:
2797
2798 @snippet example/tutorial/ext/fusion_to_hana.cpp main
2799
2800 @note
2801 At this time, only adapters to use data types from other libraries inside Hana
2802 are provided; adapters for the other way around (using Hana containers inside
2803 other libraries) are not provided.
2804
2805 However, using external adapters has a couple of pitfalls. For example, after
2806 a while using Hana, you might become used to comparing Hana tuples using the
2807 normal comparison operators, or doing arithmetic with Hana `integral_constant`s.
2808 Of course, nothing guarantees that these operators are defined for external
2809 adapters too (and in general they won't be). Hence, you'll have to stick to
2810 the functions provided by Hana that implement these operators. For example:
2811
2812 @code{cpp}
2813 auto r = std::ratio<3, 4>{} + std::ratio<4, 5>{}; // error, the operator is not defined!
2814 @endcode
2815
2816 Instead, you should use the following:
2817
2818 @snippet example/tutorial/ext/ratio_plus.cpp main
2819
2820 But sometimes, it's much worse. Some external components define operators, but
2821 they don't necessarily have the same semantics as those from Hana. For example,
2822 comparing two `std::tuple`s of different lengths will give an error when using
2823 `operator==`:
2824
2825 @code{cpp}
2826 std::make_tuple(1, 2, 3) == std::make_tuple(1, 2); // compiler error
2827 @endcode
2828
2829 On the other hand, comparing Hana tuples of different lengths will just return
2830 a false `IntegralConstant`:
2831
2832 @code{cpp}
2833 hana::make_tuple(1, 2, 3) == hana::make_tuple(1, 2); // hana::false_c
2834 @endcode
2835
2836 This is because `std::tuple` defines its own operators, and their semantics
2837 are different from that of Hana's operators. The solution is to stick with
2838 Hana's named functions instead of using operators when you know you'll have
2839 to work with other libraries:
2840
2841 @code{cpp}
2842 hana::equal(std::make_tuple(1, 2, 3), std::make_tuple(1, 2)); // hana::false_c
2843 @endcode
2844
2845 When using external adapters, one should also be careful not to forget
2846 including the proper bridge headers. For example, suppose I want to use
2847 a Boost.MPL vector with Hana. I include the appropriate bridge header:
2848
2849 @snippet example/tutorial/ext/mpl_vector.cpp front
2850
2851 @note
2852 The exact layout of these bridge headers is documented in the section about
2853 [Header organization](@ref tutorial-header_organization).
2854
2855 Now, however, suppose that I use `mpl::size` to query the size of the vector
2856 and then compare it to some value. I could also use `hana::length` and
2857 everything would be fine, but bear with me for the sake of the example:
2858
2859 @snippet example/tutorial/ext/mpl_vector.cpp size
2860
2861 The reason why this breaks is that `mpl::size` returns a MPL IntegralConstant,
2862 and Hana has no way of knowing about these unless you include the proper
2863 bridge header. Hence, you should do the following instead:
2864
2865 @snippet example/tutorial/ext/mpl_vector.cpp size-fixed
2866
2867 The morale is that when working with external libraries, you have to be a bit
2868 careful about what objects you are manipulating. The final pitfall is about
2869 implementation limits in external libraries. Many older libraries have limits
2870 regarding the maximum size of the heterogeneous containers that can be created
2871 with them. For example, one may not create a Fusion list of more than
2872 `FUSION_MAX_LIST_SIZE` elements in it. Obviously, these limits are inherited
2873 by Hana and for example, trying to compute the permutations of a `fusion::list`
2874 containing 5 elements (the resulting list would contain 120 elements) will
2875 fail in a gruesome way:
2876
2877 @code{cpp}
2878 auto list = fusion::make_list(1, 2, 3, 4, 5);
2879 auto oh_jeez = hana::permutations(list); // probably won't make it
2880 @endcode
2881
2882 Apart from the pitfalls explained in this section, using external adapters
2883 should be just as straightforward as using normal Hana containers. Of course,
2884 whenever possible, you should try to stick with Hana's containers because they
2885 are usually more friendly to work with and are often more optimized.
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896 @section tutorial-core Hana's core
2897
2898 ------------------------------------------------------------------------------
2899 The goal of this section is to give a high-level overview of Hana's core.
2900 This core is based on the notion of _tag_, which is borrowed from the
2901 Boost.Fusion and Boost.MPL libraries but taken much further by Hana. These
2902 tags are then used for several purposes, like algorithm customization,
2903 documentation grouping, improving error messages and converting containers
2904 into other containers. Because of its modular design, Hana can be extended
2905 in a ad-hoc manner very easily. In fact, all the functionality of the library
2906 is provided through an ad-hoc customization mechanism, which is explained here.
2907
2908
2909 @subsection tutorial-core-tags Tags
2910
2911 Heterogeneous programming is basically programming with objects having
2912 different types. However, it is clear that some families of objects, while
2913 having different representations (C++ types), are strongly related. For
2914 example, the `std::integral_constant<int, n>` types are different for each
2915 different `n`, but conceptually they all represent the same thing; a
2916 compile-time number. The fact that `std::integral_constant<int, 1>{}` and
2917 `std::integral_constant<int, 2>{}` have different types is just a side effect
2918 of the fact that we're using their type to encode the _value_ of these objects.
2919 Indeed, when manipulating a sequence of `std::integral_constant<int, ...>`s,
2920 chances are that you actually think of it as a homogeneous sequence of an
2921 imaginary `integral_constant` type, disregarding the actual types of the
2922 objects and pretending they are all just `integral_constant`s with different
2923 values.
2924
2925 To reflect this reality, Hana provides _tags_ representing its heterogeneous
2926 containers and other compile-time entities. For example, all of Hana's
2927 `integral_constant<int, ...>`s have different types, but they all share
2928 the same tag, `integral_constant_tag<int>`. This allows the programmer to
2929 think in terms of that single type instead of trying to think in terms of the
2930 actual types of the objects. Concretely, tags are implemented as empty `struct`s.
2931 To make them stand out, Hana adopts the convention of naming these tags by
2932 adding the `_tag` suffix.
2933
2934 @note
2935 The tag of an object of type `T` can be obtained by using `tag_of<T>::%type`,
2936 or equivalently `tag_of_t<T>`.
2937
2938 Tags are an extension to normal C++ types. Indeed, by default, the tag of a
2939 type `T` is `T` itself, and the core of the library is designed to work in
2940 those cases. For example, `hana::make` expects either a tag or an actual type;
2941 if you send it a type `T`, it will do the logical thing and construct an
2942 object of type `T` with the arguments you pass it. If you pass a tag to it,
2943 however, you should specialize `make` for that tag and provide your own
2944 implementation, as explained below. Because tags are an extension to usual
2945 types, we end up mostly reasoning in terms of tags instead of usual types,
2946 and the documentation sometimes uses the words _type_, _data type_ and _tag_
2947 interchangeably.
2948
2949
2950 @subsection tutorial-core-tag_dispatching Tag dispatching
2951
2952 Tag dispatching is a generic programming technique for picking the right
2953 implementation of a function depending on the type of the arguments passed
2954 to the function. The usual mechanism for overriding a function's behavior
2955 is overloading. Unfortunately, this mechanism is not always convenient when
2956 dealing with families of related types having different base templates, or
2957 when the kind of template parameters is not known (is it a type or a non-type
2958 template parameter?). For example, consider trying to overload a function for
2959 all Boost.Fusion vectors:
2960
2961 @code{cpp}
2962     template <typename ...T>
2963     void function(boost::fusion::vector<T...> v) {
2964         // whatever
2965     }
2966 @endcode
2967
2968 If you know Boost.Fusion, then you probably know that it won't work. This is
2969 because Boost.Fusion vectors are not necessarily specializations of the
2970 `boost::fusion::vector` template. Fusion vectors also exist in numbered
2971 forms, which are all of different types:
2972
2973 @code{cpp}
2974     boost::fusion::vector1<T>
2975     boost::fusion::vector2<T, U>
2976     boost::fusion::vector3<T, U, V>
2977     ...
2978 @endcode
2979
2980 This is an implementation detail required by the lack of variadic templates in
2981 C++03 that leaks into the interface. This is unfortunate, but we need a way to
2982 work around it. To do so, we use an infrastructure with three distinct
2983 components:
2984
2985 1. A metafunction associating a single tag to every type in a family of
2986    related types. In Hana, this tag can be accessed using the `tag_of`
2987    metafunction. Specifically, for any type `T`, `tag_of<T>::%type` is
2988    the tag used to dispatch it.
2989
2990 2. A function belonging to the public interface of the library, for which
2991    we'd like to be able to provide a customized implementation. In Hana,
2992    these functions are the algorithms associated to a concept, like
2993    `transform` or `unpack`.
2994
2995 3. An implementation for the function, parameterized with the tag(s) of the
2996    argument(s) passed to the function. In Hana, this is usually done by having
2997    a separate template called `xxx_impl` (for an interface function `xxx`)
2998    with a nested `apply` static function, as will be shown below.
2999
3000 When the public interface function `xxx` is called, it will get the tag of the
3001 argument(s) it wishes to dispatch the call on, and then forward the call to
3002 the `xxx_impl` implementation associated to those tags. For example, let's
3003 implement a basic setup for tag dispatching of a function that prints its
3004 argument to a stream. First, we define the public interface function and the
3005 implementation that can be specialized:
3006
3007 @snippet example/tutorial/tag_dispatching.cpp setup
3008
3009 Now, let's define a type that needs tag dispatching to customize the behavior
3010 of `print`. While some C++14 examples exist, they are too complicated to show
3011 in this tutorial and we will therefore use a C++03 tuple implemented as several
3012 different types to illustrate the technique:
3013
3014 @snippet example/tutorial/tag_dispatching.cpp vector
3015
3016 The nested `using hana_tag = vector_tag;` part is a terse way of controling
3017 the result of the `tag_of` metafunction, and hence the tag of the `vectorN`
3018 type. This is explained in the reference for `tag_of`. Finally, if you wanted
3019 to customize the behavior of the `print` function for all the `vectorN` types,
3020 you would normally have to write something along the lines of
3021
3022 @snippet example/tutorial/tag_dispatching.cpp old_way
3023
3024 Now, with tag dispatching, you can rely on the `vectorN`s all sharing the same
3025 tag and specialize only the `print_impl` struct instead:
3026
3027 @snippet example/tutorial/tag_dispatching.cpp customize
3028
3029 One upside is that all `vectorN`s can now be treated uniformly by the `print`
3030 function, at the cost of some boilerplate when creating the data structure
3031 (to specify the tag of each `vectorN`) and when creating the initial `print`
3032 function (to setup the tag dispatching system with `print_impl`). There are
3033 also other advantages to this technique, like the ability to check for
3034 preconditions in the interface function without having to do it in each
3035 custom implementation, which would be tedious:
3036
3037 @snippet example/tutorial/tag_dispatching.cpp preconditions
3038
3039 @note
3040 Checking preconditions does not make much sense for a `print` function, but
3041 consider for example a function to get the `n`th element of a sequence; you
3042 might want to make sure that the index is not out-of-bounds.
3043
3044 This technique also makes it easier to provide interface functions as function
3045 objects instead of normal overloaded functions, because only the interface
3046 function itself must go through the trouble of defining a function object.
3047 Function objects have several advantages over overloaded functions, like the
3048 ability to be used in higher order algorithms or as variables:
3049
3050 @snippet example/tutorial/tag_dispatching.cpp function_objects
3051
3052 As you are probably aware of, being able to implement an algorithm for many
3053 types at the same time is tremendously useful (that's precisely the goal of
3054 C++ templates!). However, even more useful is the ability to implement an
3055 algorithm for many types _that satisfy some condition_. C++ templates are
3056 currently missing this ability to constrain their template parameters, but a
3057 language feature called [concepts][C++17.clite] is being rolled out with the
3058 goal of addressing this issue.
3059
3060 With something similar in mind, Hana's algorithms support an additional layer
3061 of tag-dispatching to what was explained above. This layer allows us to
3062 "specialize" an algorithm for all types that satisfy some predicate. For
3063 example, let's say we wanted to implement the `print` function above for all
3064 types that represent some kind of sequence. Right now, we wouldn't have an
3065 easy way to do this. However, the tag dispatching for Hana's algorithms is
3066 set up slightly differently than what was shown above, and we could hence
3067 write the following:
3068
3069 @snippet example/tutorial/tag_dispatching.cpp customize-when
3070
3071 where `Tag represents some kind of sequence` would only need to be a boolean
3072 expression representing whether `Tag` is a sequence. We'll see how such
3073 predicates can be created in the next section, but for now let's assume that
3074 it _just works_. Without going into the details of how this tag-dispatching is
3075 set up, the above specialization will only be picked up when the predicate is
3076 satisfied, and if no better match can be found. Hence, for example, if our
3077 `vector_tag` was to satisfy the predicate, our initial implementation for
3078 `vector_tag` would still be preferred over the `hana::when`-based specialization,
3079 because it represents a better match. In general, any specialization (whether
3080 explicit or partial) _not_ using `hana::when` will be preferred over a
3081 specialization using `hana::when`, which was designed to be as unsurprising
3082 as possible from a user point of view. This covers pretty much all there's
3083 to say about tag-dispatching in Hana. The next section will explain how we
3084 can create C++ concepts for metaprogramming, which could then be used in
3085 conjunction with `hana::when` to achieve a great deal of expressiveness.
3086
3087
3088 @subsection tutorial-core-concepts Emulation of C++ concepts
3089
3090 The implementation of concepts in Hana is very simple. At its heart, a concept
3091 is just a template `struct` that inherits from a boolean `integral_constant`
3092 representing whether the given type is a _model_ of the concept:
3093
3094 @code{cpp}
3095 template <typename T>
3096 struct Concept
3097   : hana::integral_constant<bool, whether T models Concept>
3098 { };
3099 @endcode
3100
3101 Then, one can test whether a type `T` is a model of `Concept` by looking at
3102 `Concept<T>::%value`. Simple enough, right? Now, while the way one might
3103 implement the check does not have to be anything specific as far as Hana
3104 is concerned, the rest of this section will explain how it is usually done
3105 in Hana, and how it interacts with tag dispatching. You should then be able
3106 to define your own concepts if you so desire, or at least to understand better
3107 how Hana works internally.
3108
3109 Usually, a concept defined by Hana will require that any model implements some
3110 tag-dispatched functions. For example, the `Foldable` concept requires that
3111 any model defines at least one of `hana::unpack` and `hana::fold_left`. Of
3112 course, concepts usually also define semantic requirements (called laws) that
3113 must be satisfied by their models, but these laws are not (and couldn't be)
3114 checked by the concept. But how do we check that some functions are properly
3115 implemented? For this, we'll have to slightly modify the way we defined
3116 tag-dispatched methods as shown in the previous section. Let's go back to
3117 our `print` example and try to define a `Printable` concept for those objects
3118 that can be `print`ed. Our end goal is to have a template struct such as
3119
3120 @code{cpp}
3121 template <typename T>
3122 struct Printable
3123   : hana::integral_constant<bool, whether print_impl<tag of T> is defined>
3124 { };
3125 @endcode
3126
3127 To know whether `print_impl<...>` has been defined, we'll modify `print_impl`
3128 so that it inherits from a special base class when it is not overridden, and
3129 we'll simply check whether `print_impl<T>` inherits from that base class:
3130
3131 @snippet example/tutorial/concepts.cpp special_base_class
3132
3133 Of course, when we specialize `print_impl` with a custom type, we don't
3134 inherit from that `special_base_class` type:
3135
3136 @snippet example/tutorial/concepts.cpp special_base_class_customize
3137
3138 As you can see, `Printable<T>` really only checks whether the `print_impl<T>`
3139 struct was specialized by a custom type. In particular, it does not even check
3140 whether the nested `::%apply` function is defined or if it is syntactically
3141 valid. It is assumed that if one specializes `print_impl` for a custom type,
3142 the nested `::%apply` function exists and is correct. If it is not, a compilation
3143 error will be triggered when one tries to call `print` on an object of that type.
3144 Concepts in Hana make the same assumptions.
3145
3146 Since this pattern of inheriting from a special base class is quite abundant
3147 in Hana, the library provides a dummy type called `hana::default_` that can be
3148 used in place of `special_base_class`. Then, instead of using `std::is_base_of`,
3149 one can use `hana::is_default`, which looks nicer. With this syntactic sugar,
3150 the code now becomes:
3151
3152 @snippet example/tutorial/concepts.cpp actual
3153
3154 This is all that there's to know about the interaction between tag-dispatched
3155 functions and concepts. However, some concepts in Hana do not rely solely on
3156 the definition of specific tag-dispatched functions to determine if a type is
3157 a model of the concept. This can happen when a concept merely introduces
3158 semantic guarantees through laws and refined concepts, but no additional
3159 syntactic requirements. Defining such a concept can be useful for several
3160 reasons. First, it sometimes happen that an algorithm can be implemented
3161 more efficiently if we can assume some semantic guarantees X or Y, so we
3162 might create a concept to enforce those guarantees. Secondly, it is sometimes
3163 possible to automatically define the models for several concepts when we have
3164 additional semantic guarantees, which saves the user the trouble of defining
3165 those models manually. For example, this is the case of the `Sequence` concept,
3166 which basically adds semantic guarantees to `Iterable` and `Foldable`, and in
3167 turn allows us to define the models for a myriad of concepts ranging from
3168 `Comparable` to `Monad`.
3169
3170 For these concepts, it is usually necessary to specialize the corresponding
3171 template struct in the `boost::hana` namespace to provide a model for a custom
3172 type. Doing so is like providing a seal saying that the semantic guarantees
3173 required by the concept are respected by the custom type. The concepts that
3174 require being explicitly specialized will document that fact. So that's it!
3175 This is all that there's to know about concepts in Hana, which ends this
3176 section about the core of Hana.
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187 @section tutorial-header_organization Header organization
3188
3189 ------------------------------------------------------------------------------
3190 The library is designed to be modular while keeping the number of headers that
3191 must be included to get basic functionality reasonably low. The structure of
3192 the library was also intentionally kept simple, because we all love simplicity.
3193 What follows is a general overview of the header organization. A list of all
3194 the headers provided by the library is also available in the panel on the left
3195 (under the [Headers](files.html) label) in case you need more details.
3196
3197 - `boost/hana.hpp`\n
3198   This is the master header of the library, which includes the whole public
3199   interface of the library. Note that external adapters, experimental features
3200   and implementation details are not included by this header, however, since
3201   some of them require additional dependencies.
3202
3203 - `boost/hana/`\n
3204   This is the main directory of the library containing the definitions of
3205   everything provided by the library. Each algorithm and container provided
3206   by the library has its own header. For a container or an algorithm named
3207   `XXX`, the corresponding header is `boost/hana/XXX.hpp`.
3208
3209   - `boost/hana/concept/`\n
3210     This subdirectory contains the definition of Hana's concepts. These
3211     headers provide a way to check whether an object is a model of the
3212     corresponding concept, and they sometimes also provide default
3213     implementations for other related concepts, which are documented
3214     on a per-concept basis. They also include all the algorithms associated
3215     to that concept.
3216
3217   - `boost/hana/core/`\n
3218     This subdirectory contains the machinery for tag dispatching and other
3219     related utilities like `make` and `to`.
3220
3221   - `boost/hana/fwd/`\n
3222     This subdirectory contains the forward declaration of everything in the
3223     library. It is essentially a mirror of the `boost/hana/` directory, except
3224     all the headers contain only forward declarations and documentation. For
3225     example, to include the `hana::tuple` container, one can use the
3226     `boost/hana/tuple.hpp` header. However, if one only wants the
3227     forward declaration of that container, the `boost/hana/fwd/tuple.hpp`
3228     header can be used instead. Note that forward declarations for headers
3229     in `boost/hana/ext/` and `boost/hana/functional/` are not provided.
3230
3231   - `boost/hana/functional/`\n
3232     This subdirectory contains various function objects that are often useful,
3233     but that do not necessarily belong to a concept.
3234
3235   - `boost/hana/ext/`\n
3236     This directory contains adapters for external libraries. For a component
3237     named `xxx` in a namespace `ns`, the external adapter lives in the
3238     `boost/hana/ext/ns/xxx.hpp` header. For example, the external adapter
3239     for `std::tuple` lives in the `boost/hana/ext/std/tuple.hpp` header,
3240     while the external adapter for `boost::mpl::vector` is in
3241     `boost/hana/ext/boost/mpl/vector.hpp`.
3242
3243     Note that only the strict minimum required to adapt the external components
3244     is included in these headers (e.g. a forward declaration). This means that
3245     the definition of the external component should still be included when one
3246     wants to use it. For example:
3247     @snippet example/tutorial/include_ext.cpp main
3248
3249   - `boost/hana/experimental/`\n
3250     This directory contains experimental features that may or may not make it
3251     into the library at some point, but that were deemed useful enough to be
3252     made available to the public. Features in this subdirectory reside in the
3253     `hana::experimental` namespace. Also, do not expect these features to be
3254     stable; they may be moved, renamed, changed or removed between releases of
3255     the library. These features may also require additional external dependencies;
3256     each feature documents the additional dependencies it requires, if any.
3257
3258     Because of the potential additional dependencies, these headers are also
3259     not included by the master header of the library.
3260
3261   - `boost/hana/detail/`\n
3262     This directory contains utilities required internally. Nothing in `detail/`
3263     is guaranteed to be stable, so you should not use it.
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274 @section tutorial-conclusion Conclusion
3275
3276 ------------------------------------------------------------------------------
3277 You now have everything you need to start using the library. From this point
3278 forward, mastering the library is only a matter of understanding how to use
3279 the general purpose concepts and containers provided with it, which is best
3280 done by looking at the reference documentation. At some point, you will
3281 probably also want to create your own concepts and data types that fit your
3282 needs better; go ahead, the library was designed to be used that way.
3283
3284 @subsection tutorial-conclusion-warning Fair warning: functional programming ahead
3285
3286 Programming with heterogeneous objects is inherently functional -- since it is
3287 impossible to modify the type of an object, a new object must be introduced
3288 instead, which rules out mutation. Unlike previous metaprogramming libraries
3289 whose design was modeled on the STL, Hana uses a functional style of
3290 programming which is the source for a good portion of its expressiveness.
3291 However, as a result, many concepts presented in the reference will be
3292 unfamiliar to C++ programmers without a knowledge of functional programming.
3293 The reference attempts to make these concepts approachable by using intuition
3294 whenever possible, but bear in mind that the highest rewards are usually the
3295 fruit of some effort.
3296
3297 @subsection tutorial-conclusion-related_material Related material
3298
3299 Through the years, I have produced some material about Hana and metaprogramming
3300 more generally. You may find some of it useful:
3301
3302 - Keynote on metaprogramming at [Meeting C++][] 2016 ([slides](http://ldionne.com/meetingcpp-2016)/[video](https://youtu.be/X_p9X5RzBJE))
3303 - Talk on advanced metaprogramming techniques used in Hana at [C++Now][] 2016 ([slides](http://ldionne.com/cppnow-2016-metaprogramming-for-the-brave)/[video](https://youtu.be/UXwWXHrvTug))
3304 - Introduction to metaprogramming with Hana at [C++Now][] 2016 ([slides](http://ldionne.com/cppnow-2016-metaprogramming-for-dummies)/[video](https://youtu.be/a1doqFAumCk))
3305 - Talk on metaprogramming and Hana at [CppCon][] 2015 ([slides](http://ldionne.com/hana-cppcon-2015)/[video](https://youtu.be/cg1wOINjV9U))
3306 - Talk on metaprogramming and Hana at [C++Now][] 2015 ([slides](http://ldionne.com/hana-cppnow-2015)/[video](https://youtu.be/Z2ABRaQiFHs))
3307 - Talk on Hana at [CppCon][] 2014 ([slides](http://ldionne.com/hana-cppcon-2014)/[video](https://youtu.be/L2SktfaJPuU))
3308 - The [MPL11][] library, which is how Hana started out
3309 - Talk on the MPL11 at [C++Now][] 2014 ([slides](http://ldionne.com/mpl11-cppnow-2014)/[video](https://youtu.be/8c0aWLuEO0Y))
3310 - My bachelor's thesis was a formalization of C++ metaprogramming using category
3311   theory. The thesis is available [here](https://github.com/ldionne/hana-thesis/blob/gh-pages/main.pdf),
3312   and the slides of a related presentation are available [here](http://ldionne.com/hana-thesis).
3313   Unfortunately, both are in french only.
3314
3315
3316 This finishes the tutorial part of the documentation. I hope you enjoy using
3317 the library, and please consider [contributing][Hana.contributing] to make it
3318 even better!
3319
3320 -- Louis
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331 @section tutorial-reference Using the reference
3332
3333 ------------------------------------------------------------------------------
3334 As for most generic libraries, algorithms in Hana are documented by the
3335 concept to which they belong (`Foldable`, `Iterable`, `Searchable`, `Sequence`,
3336 etc...). The different containers are then documented on their own page, and
3337 the concepts that they model are documented there. The concepts modeled by
3338 some container defines what algorithms can be used with such a container.
3339
3340 More specifically, the structure of the reference (available in the menu to
3341 the left) goes as follow:
3342
3343 - @ref group-core\n
3344   Documentation for the core module, which contains everything needed to
3345   create concepts, data types and related utilities. This is relevant
3346   if you need to extend the library, but otherwise you can probably
3347   ignore this.
3348
3349 - @ref group-concepts\n
3350   Documentation for all the concepts provided with the library. Each concept:
3351   - Documents which functions must be implemented absolutely in order to
3352     model that concept. The set of functions that must be provided is called
3353     a _minimal complete definition_.
3354   - Documents semantic constraints that any model of that concept must satisfy.
3355     These constraints are usually called laws and they are expressed in a
3356     semi-formal mathematical language. Of course, those laws can't be checked
3357     automatically but you should still make sure you satisfy them.
3358   - Documents the concept(s) it refines, if any. Sometimes, a concept is
3359     powerful enough to provide a model of a concept it refines, or at least
3360     the implementation for some of its associated functions. When this is the
3361     case, the concept will document which functions of the refined concept it
3362     provides, and how it does so. Also, it is sometimes possible that the
3363     model for a refined concept is unique, in which case it can be provided
3364     automatically. When this happens, it will be documented but you don't have
3365     to do anything special to get that model.
3366
3367 - @ref group-datatypes\n
3368   Documentation for all the data structures provided with the library. Each
3369   data structure documents the concept(s) it models, and how it does so. It
3370   also documents the methods tied to it but not to any concept, for example
3371   `maybe` for `optional`.
3372
3373 - @ref group-functional\n
3374   General purpose function objects that are generally useful in a purely
3375   functional setting. These are currently not tied to any concept or container.
3376
3377 - @ref group-ext\n
3378   Documentation for all the adapters for external libraries. These adapters
3379   are documented as if they were native types provided by Hana, but obviously
3380   Hana only provides the compatibility layer between them and the library.
3381
3382 - @ref group-config\n
3383   Macros that can be used to tweak the global behavior of the library.
3384
3385 - @ref group-assertions\n
3386   Macros to perform various types of assertions.
3387
3388 - [<b>Alphabetical index</b>](functions.html)\n
3389   Alphabetical index of everything provided in the library.
3390
3391 - [<b>Headers</b>](files.html)\n
3392   A list of all the headers provided by the library.
3393
3394 - @ref group-details\n
3395   Implementation details; don't go there. Anything not documented at all or
3396   documented in this group is not guaranteed to be stable.
3397
3398 After you get to know Hana a bit better, it will probably happen that you just
3399 want to find the reference for a precise function, concept or container. If
3400 you know the name of what you're looking for, you can use the _search_ box
3401 located in the upper right corner of any page of the documentation. My
3402 personal experience is that this is by far the quickest way of finding
3403 what you want when you already know its name.
3404
3405
3406 @subsection tutorial-reference-signatures Function signatures
3407
3408 As you will see in the reference, several functions provide signatures
3409 documented in a semi-formal mathematical language. We are in the process
3410 of documenting all functions in this way, but this may take a while. The
3411 notation used is the usual mathematical notation for defining functions.
3412 Specifically, a function `Return f(Arg1, ..., ArgN);` can be defined
3413 equivalently using mathematical notation as
3414
3415 @f[
3416   \mathtt{f} : \mathtt{Arg}_1 \times \dots \times \mathtt{Arg}_n
3417                   \to \mathtt{Return}
3418 @f]
3419
3420 However, instead of documenting the actual argument and return types of
3421 functions, those signatures are written in terms of argument and return tags.
3422 This is done because of the heterogeneous setting, where the actual type of
3423 an object is usually pretty meaningless and does not help to reason about
3424 what's being returned or taken by a function. For example, instead of
3425 documenting the `equal` function for `integral_constant`s as
3426
3427 @f[
3428   \mathtt{equal} : \mathtt{integral\_constant<T, n>} \times
3429                    \mathtt{integral\_constant<T, m>}
3430                       \to \mathtt{integral\_constant<bool, n == m>}
3431 @f]
3432
3433 which is not really helpful (as it really presents nothing but the
3434 implementation), it is instead documented using `integral_constant_tag`,
3435 which acts as the "type" of all `integral_constant`s. Note that since `equal`
3436 is part of the `Comparable` concept, it is not _actually_ documented for
3437 `hana::integral_constant` specifically, but the idea is there:
3438
3439 @f[
3440   \mathtt{equal} : \mathtt{integral\_constant\_tag<T>} \times
3441                    \mathtt{integral\_constant\_tag<T>}
3442                       \to \mathtt{integral\_constant\_tag<bool>}
3443 @f]
3444
3445 This clearly conveys the intention that comparing two `integral_constant`s
3446 gives back another `integral_constant` holding a `bool`. In general, this
3447 abstraction of the actual representation of objects makes it possible for
3448 us to reason in a high level manner about functions, even though their
3449 actual return and argument types are heterogeneous and not helpful. Finally,
3450 most functions expect container elements to have some properties. For example,
3451 this is the case of the `sort` algorithm, which obviously requires the
3452 container elements to be `Orderable`. Normally, we would write the signature
3453 for the non-predicated version of `sort` as
3454
3455 @f[
3456   \mathtt{sort} : \mathtt{S} \to \mathtt{S} \\
3457     \text{where S is a Sequence}
3458 @f]
3459
3460 However, this fails to express the requirement that the contents of `S` are
3461 `Orderable`. To express this, we use the following notation:
3462
3463 @f[
3464   \mathtt{sort} : \mathtt{S(T)} \to \mathtt{S(T)} \\
3465     \text{where S is a Sequence and T is Orderable}
3466 @f]
3467
3468 One way to see this is to pretend that `S`, the sequence tag, is actually
3469 parameterized by the tag of the sequence's elements, `T`. We're also pretending
3470 that the elements all have the same tag `T`, which is not the case in general.
3471 Now, by stating that `T` must be `Orderable`, we're expressing the fact that
3472 the sequence's elements must be `Orderable`. This notation is used in different
3473 flavors to express different kinds of requirements. For example, the
3474 `cartesian_product` algorithm takes a sequence of sequences and returns the
3475 cartesian product of those sequences as a sequence of sequences. Using our
3476 notation, this can be conveyed very easily:
3477
3478 @f[
3479   \mathtt{cartesian\_product} : \mathtt{S(S(T))} \to \mathtt{S(S(T))} \\
3480     \text{where S is a Sequence}
3481 @f]
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492 @section tutorial-acknowledgements Acknowledgements
3493
3494 ------------------------------------------------------------------------------
3495 I'd like to thank the following persons and organizations for contributing to
3496 Hana in one way or another:
3497
3498 - Zach Laine and Matt Calabrese for the original idea of using function call
3499   syntax to do type-level computations, as presented in their BoostCon
3500   [presentation][video.inst_must_go] ([slides 1][slides.inst_must_go1])
3501   ([slides 2][slides.inst_must_go2]).
3502 - Joel Falcou for mentoring me two consecutive years during my work on Hana
3503   as part of the [Google Summer of Code][GSoC] program, Niall Douglas for
3504   being the GSoC admin for Boost and helping me get in the program, and
3505   finally Google for their awesome GSoC program.
3506 - The [Boost Steering committee][Boost.Steering] for unlocking a grant for me
3507   to work on Hana in the winter of 2015, as an extension to the previous
3508   year's GSoC.
3509 - Several [C++Now][] attendees and members of the [Boost mailing list]
3510   [Boost.Devel] for insightful conversations, comments and questions
3511   about the project.
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522 @section tutorial-glossary Glossary
3523
3524 ------------------------------------------------------------------------------
3525 The reference documentation uses a couple of terms that are specific to this
3526 library. Also, a simplified implementation of functions is sometimes provided
3527 in pseudo-code, the actual implementation sometimes being slightly hard to
3528 understand. This section defines terms used in the reference and in the
3529 pseudo-code used to describe some functions.
3530
3531 @anchor tutorial-glossary-forwarded
3532 #### `forwarded(x)`
3533 Means that the object is forwarded optimally. This means that if `x` is a
3534 parameter, it is `std::forward`ed, and if it is a captured variable, it is
3535 moved from whenever the enclosing lambda is an rvalue.
3536
3537 Also note that when `x` can be moved from, the statement `return forwarded(x);`
3538 in a function with `decltype(auto)` does not mean that an rvalue reference to
3539 `x` will be returned, which would create a dangling reference. Rather, it
3540 means that `x` is returned by value, the value being constructed with the
3541 `std::forward`ed `x`.
3542
3543 @anchor tutorial-glossary-perfect_capture
3544 #### `perfect-capture`
3545 This is used in lambdas to signify that the captured variables are
3546 initialized using perfect forwarding, as if `[x(forwarded(x))...]() { }`
3547 had been used.
3548
3549 @anchor tutorial-glossary-tag_dispatched
3550 #### `tag-dispatched`
3551 This means that the documented function uses [tag dispatching]
3552 (@ref tutorial-core-tag_dispatching), and hence the exact
3553 implementation depends on the model of the concept associated
3554 to the function.
3555
3556 @anchor tutorial-glossary-implementation_defined
3557 #### `implementation-defined`
3558 This expresses the fact that the exact implementation of an entity (usually a
3559 type) should not be relied upon by users. In particular, this means that one
3560 can not assume anything beyond what is written explicitly in the documentation.
3561 Usually, the concepts satisfied by an implementation-defined entity will be
3562 documented, because one could otherwise do nothing with it. Concretely,
3563 assuming too much about an implementation-defined entity will probably
3564 not kill you, but it will very probably break your code when you update
3565 to a newer version of Hana.
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576 @section tutorial-rationales Rationales/FAQ
3577
3578 ------------------------------------------------------------------------------
3579 This section documents the rationale for some design choices. It also serves
3580 as a FAQ for some (not so) frequently asked questions. If you think something
3581 should be added to this list, open a GitHub issue and we'll consider either
3582 improving the documentation or adding the question here.
3583
3584
3585 @subsection tutorial-rationales-dependencies Why restrict usage of external dependencies?
3586
3587 There are several reasons for doing so. First, Hana is a very fundamental
3588 library; we are basically reimplementing the core language and the standard
3589 library with support for heterogeneous types. When going through the code,
3590 one quickly realizes that other libraries are rarely needed, and that almost
3591 everything has to be implemented from scratch. Also, since Hana is very
3592 fundamental, there is even more incentive for keeping the dependencies
3593 minimal, because those dependencies will be handed down to the users.
3594 Regarding the minimal reliance on Boost in particular, one big argument
3595 for using it is portability. However, as a cutting edge library, Hana only
3596 targets very recent compilers. Hence, we can afford to depend on modern
3597 constructs and the portability given to us by using Boost would mostly
3598 represent dead weight.
3599
3600
3601 @subsection tutorial-rationales-iterators Why no iterators?
3602
3603 Iterator based designs have their own merits, but they are also known to
3604 reduce the composability of algorithms. Furthermore, the context of
3605 heterogeneous programming brings a lot of points that make iterators much
3606 less interesting. For example, incrementing an iterator would have to return
3607 a new iterator with a different type, because the type of the new object it
3608 is pointing to in the sequence might be different. It also turns out that
3609 implementing most algorithms in terms of iterators leads to a worse
3610 compile-time performance, simply because the execution model of metaprogramming
3611 (using the compiler as an interpreter) is so different from the runtime
3612 execution model of C++ (a processor accessing contiguous memory).
3613
3614
3615 @subsection tutorial-rationales-container_representation Why leave some container's representation implementation-defined?
3616
3617 First, it gives much more wiggle room for the implementation to perform
3618 compile-time and runtime optimizations by using clever representations for
3619 specific containers. For example, a tuple containing homogeneous objects of
3620 type `T` could be implemented as an array of type `T` instead, which is more
3621 efficient at compile-time. Secondly, and most importantly, it turns out that
3622 knowing the type of a _heterogeneous_ container is not as useful as you would
3623 think. Indeed, in the context of heterogeneous programming, the type of the
3624 object returned by a computation is usually part of the computation too. In
3625 other words, there is no way to know the type of the object returned by an
3626 algorithm without actually performing the algorithm. For example, consider
3627 the `find_if` algorithm:
3628
3629 @snippet example/tutorial/rationale.container.cpp hana
3630
3631 If the predicate is satisfied for some element of the tuple, result will be
3632 equal to `just(x)`. Otherwise, `result` will be equal to `nothing`. However,
3633 the `nothing`ness of the result is known at compile-time, which requires
3634 `just(x)` and `nothing` to have different types. Now, say you wanted to
3635 explicitly write the type of the result:
3636
3637 @snippet example/tutorial/rationale.container.cpp hana-explicit
3638
3639 In order to possess the knowledge of what `some_type` is, you would need to
3640 actually perform the algorithm, because `some_type` depends on whether the
3641 predicate is satisfied or not for some element in the container. In other
3642 words, if you were able to write the above, then you would already know what
3643 the result of the algorithm is and you would not need to perform the algorithm
3644 in the first place. In Boost.Fusion, this problem is addressed by having a
3645 separate `result_of` namespace, which contains a metafunction computing the
3646 result type of any algorithm given the types of the arguments passed to it.
3647 For example, the above example could be rewritten with Fusion as:
3648
3649 @snippet example/tutorial/rationale.container.cpp fusion
3650
3651 Notice that we're basically doing the computation twice; once in the `result_of`
3652 namespace and once in the normal `fusion` namespace, which is highly redundant.
3653 Before the days of `auto` and `decltype`, such techniques were necessary to
3654 perform heterogeneous computations. However, since the advent of modern C++,
3655 the need for explicit return types in the context of heterogeneous programming
3656 is largely obsolete, and knowing the actual type of containers is usually not
3657 that useful.
3658
3659
3660 @subsection tutorial-rationales-why_Hana Why Hana?
3661
3662 No, it isn't the name of my girlfriend! I just needed a short and good looking
3663 name that people would easily remember, and Hana came up. It also came to my
3664 attention that Hana means _flower_ in Japanese, and _one_ in Korean. Since
3665 Hana is pretty and it unifies type-level and heterogeneous programming under
3666 a single paradigm, the name appears to be quite well chosen in retrospect :-).
3667
3668
3669 @subsection tutorial-rationales-tuple Why define our own tuple?
3670
3671 Since Hana defines a lot of algorithms on tuples, a possible way to go would
3672 have been to simply use `std::tuple` and provide the algorithms only, instead
3673 of also providing our own tuple. The reason for providing our own tuple is
3674 principally performance. Indeed, all the `std::tuple` implementations tested
3675 so far have a very bad compile-time performance. Also, to get truly amazing
3676 compile-time performance, we need to take advantage of the tuple's internal
3677 representation in some algorithms, which requires defining our own. Finally,
3678 some sugar like `operator[]` could not be provided if we were using a
3679 `std::tuple`, since that operator must be defined as a member function.
3680
3681
3682 @subsection tutorial-rationales-naming How are names chosen?
3683
3684 When deciding upon a name `X`, I try to balance the following things
3685 (in no specific order):
3686
3687 - How idiomatic is `X` in C++?
3688 - How idiomatic is `X` in the rest of the programming world?
3689 - How good of a name `X` _actually is_, regardless of historical reasons
3690 - How do I, as the library author, feel about `X`
3691 - How do users of the library feel about `X`
3692 - Are there technical reasons not to use `X`, like name clashes or names
3693   reserved by the standard
3694
3695 Of course, good naming is and will always be hard. Names are and will always
3696 be tainted by the author's own bias. Still, I try to choose names in a
3697 reasonable manner.
3698
3699
3700 @subsection tutorial-rationales-parameters How is the parameter order decided?
3701
3702 Unlike naming, which is fairly subjective, the order of the parameters of a
3703 function is usually pretty straightforward to determine. Basically, the rule
3704 of thumb is "the container goes first". It has always been this way in Fusion
3705 and MPL, and this is intuitive for most C++ programmers. Also, in higher-order
3706 algorithms, I try to put the function parameter last, so that multi-line
3707 lambdas look nice:
3708
3709 @code{cpp}
3710 algorithm(container, [](auto x) {
3711   return ...;
3712 });
3713
3714 // is nicer than
3715
3716 algorithm([](auto x) {
3717   return ...;
3718 }, container);
3719 @endcode
3720
3721
3722 @subsection tutorial-rationales-tag_dispatching Why tag dispatching?
3723
3724 There are several different techniques we could have used to provide
3725 customization points in the library, and tag-dispatching was chosen. Why?
3726 First, I wanted a two-layer dispatching system because this allows functions
3727 from the first layer (the ones that are called by users) to actually be
3728 function objects, which allows passing them to higher-order algorithms.
3729 Using a dispatching system with two layers also allows adding some
3730 compile-time sanity checks to the first layer, which improves error messages.
3731
3732 Now, tag-dispatching was chosen over other techniques with two layers for a
3733 couple of reasons. First, having to explicitly state how some tag is a model
3734 of a concept gives the responsibility of making sure that the semantic
3735 requirements of the concept are respected to the user. Secondly, when checking
3736 whether a type is a model of some concept, we basically check that some key
3737 functions are implemented. In particular, we check that the functions from the
3738 minimal complete definition of that concept are implemented. For example,
3739 `Iterable<T>` checks whether the `is_empty`, `at` and `drop_front` functions
3740 implemented for `T`. However, the only way to detect this without
3741 tag-dispatching is to basically check whether the following expressions
3742 are valid in a SFINAE-able context:
3743
3744 @code{cpp}
3745 implementation_of_at(std::declval<T>(), std::declval<N>())
3746 implementation_of_is_empty(std::declval<T>())
3747 implementation_of_drop_front(std::declval<T>())
3748 @endcode
3749
3750 Unfortunately, this requires actually doing the algorithms, which might either
3751 trigger a hard compile-time error or hurt compile-time performance. Also, this
3752 requires picking an arbitrary index `N` to call `at` with: what if the `Iterable`
3753 is empty? With tag dispatching, we can just ask whether `at_impl<T>`,
3754 `is_empty_impl<T>` and `drop_front_impl<T>` are defined, and nothing happens
3755 until we actually call their nested `::%apply` function.
3756
3757
3758 @subsection tutorial-rationales-zip_longest Why not provide zip_longest?
3759
3760 It would require either (1) padding the shortest sequences with an arbitrary
3761 object, or (2) padding the shortest sequences with an object provided by the
3762 user when calling `zip_longest`. Since there is no requirement that all the
3763 zipped sequences have elements of similar types, there is no way to provide a
3764 single consistent padding object in all cases. A tuple of padding objects
3765 should be provided, but I find it perhaps too complicated to be worth it for
3766 now. If you need this functionality, open a GitHub issue.
3767
3768
3769 @subsection tutorial-rationales-concepts Why aren't concepts constexpr functions?
3770
3771 Since the C++ concept proposal maps concepts to boolean `constexpr` functions,
3772 it would make sense that Hana defines its concepts as such too, instead of as
3773 structs with a nested `::%value`. Indeed, this was the first choice, but it
3774 had to be revised because template functions have one limitation that makes
3775 them less flexible. Specifically, a template function can't be passed to a
3776 higher-order metafunction. In other words, it is not possible to write the
3777 following
3778
3779 @code{cpp}
3780 template <??? Concept>
3781 struct some_metafunction {
3782   // ...
3783 };
3784 @endcode
3785
3786 This sort of code is very useful in some contexts, such as checking whether
3787 two types have a common embedding modeling a concept:
3788
3789 @code{cpp}
3790 template <??? Concept, typename T, typename U>
3791 struct have_common_embedding {
3792   // whether T and U both model Concept, and share a common type that also models Concept
3793 };
3794 @endcode
3795
3796 With concepts as boolean `constexpr` functions, this can't be written
3797 generically. When concepts are just template structs, however, we can
3798 use template template parameters:
3799
3800 @code{cpp}
3801 template <template <typename ...> class Concept, typename T, typename U>
3802 struct have_common_embedding {
3803   // whether T and U both model Concept, and share a common type that also models Concept
3804 };
3805 @endcode
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816 @section tutorial-appendix-constexpr Appendix I: Advanced constexpr
3817
3818 ------------------------------------------------------------------------------
3819 In C++, the border between compile-time and runtime is hazy, a fact that is
3820 even more true with the introduction of [generalized constant expressions]
3821 [C++14.gconstexpr] in C++14. However, being able to manipulate heterogeneous
3822 objects is all about understanding that border and then crossing it at one's
3823 will. The goal of this section is to set things straight with `constexpr`; to
3824 understand which problems it can solve and which ones it can't. This section
3825 covers advanced concepts about to constant expressions; only readers with a
3826 good understanding of `constexpr` should attempt to read this.
3827
3828
3829 @subsection tutorial-appendix-constexpr-stripping Constexpr stripping
3830
3831 Let's start with a challenging question. Should the following code compile?
3832
3833 @code{cpp}
3834 template <typename T>
3835 void f(T t) {
3836   static_assert(t == 1, "");
3837 }
3838
3839 constexpr int one = 1;
3840 f(one);
3841 @endcode
3842
3843 The answer is no, and the error given by Clang goes like
3844
3845 @code{cpp}
3846 error: static_assert expression is not an integral constant expression
3847   static_assert(t == 1, "");
3848                 ^~~~~~
3849 @endcode
3850
3851 The explanation is that inside of `f`'s body, `t` is not a constant expression,
3852 and hence it can't be used as the operand to a `static_assert`. The reason is
3853 that such a function simply can't be generated by the compiler. To understand
3854 the issue, consider what should happen when we instantiate the `f` template
3855 with a concrete type:
3856
3857 @code{cpp}
3858 // Here, the compiler should generate the code for f<int> and store the
3859 // address of that code into fptr.
3860 void (*fptr)(int) = f<int>;
3861 @endcode
3862
3863 Clearly, the compiler can't generate `f<int>`'s code, which should trigger a
3864 `static_assert` if `t != 1`, because we haven't specified `t` yet. Even worse,
3865 the generated function should work on both constant and non-constant
3866 expressions:
3867
3868 @code{cpp}
3869 void (*fptr)(int) = f<int>; // assume this was possible
3870 int i = ...; // user input
3871 fptr(i);
3872 @endcode
3873
3874 Clearly, `fptr`'s code can't be generated, because it would require being able
3875 to `static_assert` on a runtime value, which does not make sense. Furthermore,
3876 note that it does not matter whether you make the function `constexpr` or not;
3877 making `f` `constexpr` would only state that the _result_ of `f` is a constant
3878 expression whenever its argument is a constant expression, but it still does
3879 not give you the ability to know whether you were called with a constant
3880 expression from `f`'s body. In other words, what we would want is something
3881 like:
3882
3883 @code{cpp}
3884 template <typename T>
3885 void f(constexpr T t) {
3886   static_assert(t == 1, "");
3887 }
3888
3889 constexpr int one = 1;
3890 f(one);
3891 @endcode
3892
3893 In this hypothetical scenario, the compiler would know that `t` is a constant
3894 expression from the body of `f`, and the `static_assert` could be made to work.
3895 However, `constexpr` parameters do not exist in the current language, and
3896 adding them would bring up very challenging design and implementation issues.
3897 The conclusion of this little experiment is that __argument passing strips
3898 away `constexpr`-ness__. What might be unclear by now are the consequences
3899 of this stripping, which are explained next.
3900
3901
3902 @subsection tutorial-tutorial-appendix-constexpr-preservation Constexpr preservation
3903
3904 The fact that an argument is not a constant expression means that we can't use
3905 it as a non-type template parameter, as an array bound, inside a `static_assert`
3906 or anything else that requires a constant expression. In addition, this means
3907 that the return type of a function can't depend on the _value_ of an argument
3908 which is nothing new if you think about it:
3909
3910 @code{cpp}
3911     template <int i>
3912     struct foo { };
3913
3914     auto f(int i) -> foo<i>; // obviously won't work
3915 @endcode
3916
3917 In fact, the return type of a function may only depend on the types of its
3918 arguments, and `constexpr` can't change this fact. This is of utmost importance
3919 to us, because we're interested in manipulating heterogeneous objects, which
3920 eventually means returning objects with different types depending on the
3921 argument of the function. For example, a function might want to return an
3922 object of type `T` in one case and an object of type `U` in the other;
3923 from our analysis, we now know that these "cases" will have to depend on
3924 information encoded in the _types_ of the arguments, not in their _values_.
3925
3926 To preserve `constexpr`-ness through argument passing, we have to encode the
3927 `constexpr` value into a type, and then pass a not-necessarily-`constexpr`
3928 object of that type to the function. The function, which must be a template,
3929 may then access the `constexpr` value encoded inside that type.
3930
3931 @todo
3932 Improve this explanation and talk about non-integral constant expressions
3933 wrapped into types.
3934
3935
3936 @subsection tutorial-appendix-constexpr-effects Side effects
3937
3938 Let me ask a tricky question. Is the following code valid?
3939
3940 @code{cpp}
3941 template <typename T>
3942 constexpr int f(T& n) { return 1; }
3943
3944 int n = 0;
3945 constexpr int i = f(n);
3946 @endcode
3947
3948 The answer is _yes_, but the reason might not be obvious at first. What
3949 happens here is that we have a non-`constexpr` `int n`, and a `constexpr`
3950 function `f` taking a reference to its argument. The reason why most people
3951 think it shouldn't work is that `n` is not `constexpr`. However, we're not
3952 doing anything with `n` inside of `f`, so there is no actual reason why this
3953 shouldn't work! This is a bit like `throw`ing inside of a `constexpr` function:
3954
3955 @code{cpp}
3956 constexpr int sqrt(int i) {
3957   if (i < 0) throw "i should be non-negative";
3958
3959   return ...;
3960 }
3961
3962 constexpr int two = sqrt(4); // ok: did not attempt to throw
3963 constexpr int error = sqrt(-4); // error: can't throw in a constant expression
3964 @endcode
3965
3966 As long as the code path where `throw` appears is not executed, the result of
3967 the invocation can be a constant expression. Similarly, we can do whatever we
3968 want inside of `f`, as long as we don't execute a code path that requires
3969 accessing its argument `n`, which is not a constant expression:
3970
3971 @code{cpp}
3972 template <typename T>
3973 constexpr int f(T& n, bool touch_n) {
3974   if (touch_n) n + 1;
3975   return 1;
3976 }
3977
3978 int n = 0;
3979 constexpr int i = f(n, false); // ok
3980 constexpr int j = f(n, true); // error
3981 @endcode
3982
3983 The error given by Clang for the second invocation is
3984
3985 @code{cpp}
3986 error: constexpr variable 'j' must be initialized by a constant expression
3987 constexpr int j = f(n, true); // error
3988               ^   ~~~~~~~~~~
3989 note: read of non-const variable 'n' is not allowed in a constant expression
3990   if (touch_n) n + 1;
3991                ^
3992 @endcode
3993
3994 Let's now step the game up a bit and consider a more subtle example.
3995 Is the following code valid?
3996
3997 @code{cpp}
3998 template <typename T>
3999 constexpr int f(T n) { return 1; }
4000
4001 int n = 0;
4002 constexpr int i = f(n);
4003 @endcode
4004
4005 The only difference with our initial scenario is that `f` now takes its
4006 argument by value instead of by reference. However, this makes a world of
4007 difference. Indeed, we're now asking the compiler to make a copy of `n`
4008 and to pass this copy to `f`. However, `n` is not `constexpr`, so its
4009 value is only known at runtime. How could the compiler make a copy (at
4010 compile-time) of a variable whose value is only known at runtime? Of
4011 course, it can't. Indeed, the error message given by Clang is pretty
4012 explicit about what's happening:
4013
4014 @code{cpp}
4015 error: constexpr variable 'i' must be initialized by a constant expression
4016 constexpr int i = f(n);
4017               ^   ~~~~
4018 note: read of non-const variable 'n' is not allowed in a constant expression
4019 constexpr int i = f(n);
4020                     ^
4021 @endcode
4022
4023 @todo
4024 Explain how side-effects may not appear inside constant expressions, even
4025 if the expression they yield are not accessed.
4026
4027 <!-------------------
4028 Let me ask a tricky question. Is the following code valid?
4029
4030 @code{cpp}
4031   template <typename X>
4032   auto identity(X x) { return x; }
4033
4034   static_assert(value(identity(bool_c<true>)), "");
4035 @endcode
4036
4037 The answer is "no", but the reason might not be obvious at first. Even more
4038 puzzling is that the following code is perfectly valid:
4039
4040 @snippet example/tutorial/constant_side_effects.cpp pure
4041
4042 To understand why the compiler can't possibly evaluate the first assertion
4043 at compile-time, notice that `identity` was not marked `constexpr` and
4044 consider the following alternative (but valid) definition for `identity`:
4045
4046 @snippet example/tutorial/constant_side_effects.cpp impure_identity
4047
4048 The signature of the function did not change; the function could even have
4049 been defined in a separate source file. However, it is now obvious that the
4050 compiler can't evaluate that expression at compile-time. On the other hand,
4051 when we write
4052
4053 @snippet example/tutorial/constant_side_effects.cpp impure
4054
4055 we're telling the compiler to perform those potential side effects during the
4056 dynamic initialization phase! Then, we use `value` to return the compile-time
4057 value associated to its argument. Also note that `value` takes a `const&` to
4058 its argument; if it tried taking it by value, we would be reading from a
4059 non-`constexpr` variable to do the copying, and that could hide side-effects.
4060 ------>
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071 @section tutorial-appendix-MPL Appendix II: A minimal MPL
4072
4073 ------------------------------------------------------------------------------
4074 This section presents a mini reimplementation of the MPL library. The goal is
4075 to be as backward compatible as possible with the MPL, while still using Hana
4076 under the hood. Only the "Algorithms" part of the MPL is implemented as a case
4077 study, but it should be possible to implement many (but not all) metafunctions
4078 of the MPL.
4079
4080 Scroll down to the `main` function to see the tests. The tests are exactly
4081 the examples in the MPL documentation that were copy/pasted and then
4082 modified as little as possible to work with this reimplementation.
4083
4084 @include example/tutorial/appendix_mpl.cpp
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095 <!-- Links -->
4096 [Boost.Devel]: http://lists.boost.org/Archives/boost
4097 [Boost.Fusion]: http://www.boost.org/doc/libs/release/libs/fusion/doc/html/index.html
4098 [Boost.MPL]: http://www.boost.org/doc/libs/release/libs/mpl/doc/index.html
4099 [Boost.Steering]: https://sites.google.com/a/boost.org/steering/home
4100 [Boost]: http://www.boost.org
4101 [Brigand]: https://github.com/edouarda/brigand
4102 [C++14.auto_rt]: http://en.wikipedia.org/wiki/C%2B%2B14#Function_return_type_deduction
4103 [C++14.gconstexpr]: http://en.wikipedia.org/wiki/C%2B%2B11#constexpr_.E2.80.93_Generalized_constant_expressions
4104 [C++14.glambda]: http://en.wikipedia.org/wiki/C%2B%2B14#Generic_lambdas
4105 [C++14.ice]: http://en.cppreference.com/w/cpp/types/integral_constant
4106 [C++14.udl]: http://en.wikipedia.org/wiki/C%2B%2B11#User-defined_literals
4107 [C++14.vtemplate]: http://en.wikipedia.org/wiki/C%2B%2B14#Variable_templates
4108 [C++14]: http://en.wikipedia.org/wiki/C%2B%2B14
4109 [C++17.clite]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf
4110 [C++Now]: http://cppnow.org
4111 [Chandler.MeetingC++]: https://youtu.be/qkzaZumt_uk?t=4478
4112 [CMake]: http://www.cmake.org
4113 [constexpr_throw]: http://stackoverflow.com/a/8626450/627587
4114 [CopyConstructible]: http://en.cppreference.com/w/cpp/concept/CopyConstructible
4115 [CppCon]: http://cppcon.org
4116 [GOTW]: http://www.gotw.ca/gotw/index.htm
4117 [GSoC]: http://www.google-melange.com/gsoc/homepage/google/gsoc2014
4118 [Hana.chat]: https://gitter.im/boostorg/hana
4119 [Hana.contributing]: https://github.com/boostorg/hana/blob/master/CONTRIBUTING.md#how-to-contribute
4120 [Hana.findmodule]: https://github.com/boostorg/hana/blob/master/cmake/FindHana.cmake
4121 [Hana.hacking]: https://github.com/boostorg/hana/blob/master/README.md#hacking-on-hana
4122 [Hana.issues]: https://github.com/boostorg/hana/issues
4123 [Hana.repository]: https://github.com/boostorg/hana
4124 [Hana.StackOverflow]: http://stackoverflow.com/questions/tagged/boost-hana
4125 [Hana.wiki]: https://github.com/boostorg/hana/wiki
4126 [Homebrew]: http://brew.sh
4127 [lie-to-children]: http://en.wikipedia.org/wiki/Lie-to-children
4128 [Meeting C++]: https://meetingcpp.com
4129 [Metabench]: http://metaben.ch
4130 [MPL.arithmetic]: http://www.boost.org/doc/libs/release/libs/mpl/doc/refmanual/arithmetic-operations.html
4131 [MPL.metafunction]: http://www.boost.org/doc/libs/release/libs/mpl/doc/refmanual/metafunction.html
4132 [MPL.mfc]: http://www.boost.org/doc/libs/release/libs/mpl/doc/refmanual/metafunction-class.html
4133 [MPL11]: http://github.com/ldionne/mpl11
4134 [N4461]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4461.html
4135 [N4487]: https://isocpp.org/files/papers/N4487.pdf
4136 [pkg-config]: http://www.freedesktop.org/wiki/Software/pkg-config/
4137 [POD]: http://en.cppreference.com/w/cpp/concept/PODType
4138 [SFINAE]: http://en.cppreference.com/w/cpp/language/sfinae
4139 [slides.inst_must_go1]: https://github.com/boostcon/2010_presentations/raw/master/mon/instantiations_must_go.pdf
4140 [slides.inst_must_go2]: https://github.com/boostcon/2010_presentations/raw/master/mon/instantiations_must_go_2.pdf
4141 [SO.sfinae]: http://stackoverflow.com/a/257382/627587
4142 [Sprout]: https://github.com/bolero-MURAKAMI/Sprout
4143 [StackOverflow]: http://stackoverflow.com
4144 [video.inst_must_go]: https://www.youtube.com/watch?v=x7UmrRzKAXU
4145
4146 */