1//// 2Copyright 2017 Peter Dimov 3 4Distributed under the Boost Software License, Version 1.0. 5 6See accompanying file LICENSE_1_0.txt or copy at 7http://www.boost.org/LICENSE_1_0.txt 8//// 9 10[#examples] 11# Examples 12:toc: 13:toc-title: 14:idprefix: 15 16## Generating Test Cases 17 18Let's suppose that we have written a metafunction `result<T, U>`: 19 20``` 21template<class T> using promote = typename std::common_type<T, int>::type; 22 23template<class T, class U> using result = 24 typename std::common_type<promote<T>, promote<U>>::type; 25``` 26 27that ought to represent the result of an arithmetic operation on the integer types `T` and `U`, 28for example `t + u`. We want to test whether `result<T, U>` gives correct results for various combinations 29of `T` and `U`, so we write the function 30``` 31template<class T1, class T2> void test_result() 32{ 33 using T3 = decltype( T1() + T2() ); 34 using T4 = result<T1, T2>; 35 36 std::cout << ( std::is_same<T3, T4>::value? "[PASS]": "[FAIL]" ) << std::endl; 37} 38``` 39and then need to call it a substantial number of times: 40 41 int main() 42 { 43 test_result<char, char>(); 44 test_result<char, short>(); 45 test_result<char, int>(); 46 test_result<char, unsigned>(); 47 // ... 48 } 49 50Writing all those type combinations by hand is unwieldy, error prone, and worst of all, boring. This is 51how we can leverage Mp11 to automate the task: 52``` 53#include <boost/mp11.hpp> 54#include <boost/core/demangle.hpp> 55#include <type_traits> 56#include <iostream> 57#include <typeinfo> 58 59using namespace boost::mp11; 60 61template<class T> std::string name() 62{ 63 return boost::core::demangle( typeid(T).name() ); 64} 65 66template<class T> using promote = typename std::common_type<T, int>::type; 67 68template<class T, class U> using result = 69 typename std::common_type<promote<T>, promote<U>>::type; 70 71template<class T1, class T2> void test_result( mp_list<T1, T2> const& ) 72{ 73 using T3 = decltype( T1() + T2() ); 74 using T4 = result<T1, T2>; 75 76 std::cout << ( std::is_same<T3, T4>::value? "[PASS] ": "[FAIL] " ) 77 << name<T1>() << " + " << name<T2>() << " -> " << name<T3>() 78 << ", result: " << name<T4>() << std::endl; 79} 80 81int main() 82{ 83 using L = std::tuple<char, short, int, unsigned, long, unsigned long>; 84 tuple_for_each( mp_product<mp_list, L, L>(), [](auto&& x){ test_result(x); } ); 85} 86``` 87How does it work? 88 89`mp_product<F, L1, L2>` calls `F<T1, T2>` where `T1` varies over the elements of `L1` and `T2` varies over 90the elements of `L2`, as if by executing two nested loops. It then returns a list of these results, of the same 91type as `L1`. 92 93In our case, both lists are the same `std::tuple`, and `F` is `mp_list`, so `mp_product<mp_list, L, L>` will get us 94`std::tuple<mp_list<char, char>, mp_list<char, short>, mp_list<char, int>, ..., mp_list<unsigned long, long>, mp_list<unsigned long, unsigned long>>`. 95 96We then default-construct this tuple and pass it to `tuple_for_each`. `tuple_for_each(tp, f)` calls `f` for every 97tuple element; we use a (C++14) lambda that calls `test_result`. 98 99In pure C++11, we can't use a lambda with an `auto&&` parameter, so we'll have to make `test_result` a function object with 100a templated `operator()` and pass that to `tuple_for_each` directly: 101``` 102struct test_result 103{ 104 template<class T1, class T2> void operator()( mp_list<T1, T2> const& ) const 105 { 106 using T3 = decltype( T1() + T2() ); 107 using T4 = result<T1, T2>; 108 109 std::cout << ( std::is_same<T3, T4>::value? "[PASS] ": "[FAIL] " ) 110 << name<T1>() << " + " << name<T2>() << " -> " << name<T3>() 111 << ", result: " << name<T4>() << std::endl; 112 } 113}; 114 115int main() 116{ 117 using L = std::tuple<char, short, int, unsigned, long, unsigned long>; 118 tuple_for_each( mp_product<mp_list, L, L>(), test_result() ); 119} 120``` 121## Writing common_type Specializations 122 123The standard trait `std::common_type`, used to obtain a type to which all of its arguments can convert without 124unnecessary loss of precision, can be user-specialized when its default implementation (based on the ternary `?:` 125operator) is unsuitable. 126 127Let's write a `common_type` specialization for two `std::tuple` arguments. For that, we need a metafunction that 128applies `std::common_type` to each pair of elements and gathers the results into a tuple: 129``` 130template<class... T> using common_type_t = 131 typename std::common_type<T...>::type; // standard in C++14 132 133template<class Tp1, class Tp2> using common_tuple = 134 mp_transform<common_type_t, Tp1, Tp2>; 135``` 136then specialize `common_type` to use it: 137``` 138namespace std 139{ 140 141 template<class... T1, class... T2> 142 struct common_type<std::tuple<T1...>, std::tuple<T2...>>: 143 mp_defer<common_tuple, std::tuple<T1...>, std::tuple<T2...>> 144 { 145 }; 146 147} // std 148``` 149(There is no need to specialize `std::common_type` for more than two arguments - it takes care of synthesizing the appropriate semantics from 150the binary case.) 151 152The subtlety here is the use of `mp_defer`. We could have defined a nested `type` to `common_tuple<std::tuple<T1...>, std::tuple<T2...>>`, 153and it would still have worked in all valid cases. By letting `mp_defer` define `type`, though, we make our specialization _SFINAE-friendly_. 154 155That is, when our `common_tuple` causes a substitution failure instead of a hard error, `mp_defer` will not define a nested `type`, 156and `common_type_t`, which is defined as `typename common_type<...>::type`, will also cause a substitution failure. 157 158As another example, consider the hypothetical type `expected<T, E...>` that represents either a successful return with a value of `T`, 159or an unsuccessful return with an error code of some type in the list `E...`. The common type of `expected<T1, E1, E2, E3>` and 160`expected<T2, E1, E4, E5>` is `expected<common_type_t<T1, T2>, E1, E2, E3, E4, E5>`. That is, the possible return values are 161combined into their common type, and we take the union of the set of error types. 162 163Therefore, 164``` 165template<class T1, class E1, class T2, class E2> using common_expected = 166 mp_rename<mp_push_front<mp_unique<mp_append<E1, E2>>, common_type_t<T1, T2>>, 167 expected>; 168 169namespace std 170{ 171 172 template<class T1, class... E1, class T2, class... E2> 173 struct common_type<expected<T1, E1...>, expected<T2, E2...>>: 174 mp_defer<common_expected, T1, mp_list<E1...>, T2, mp_list<E2...>> 175 { 176 }; 177 178} // std 179``` 180Here we've taken a different tack; instead of passing the `expected` types to `common_expected`, we're passing the `T` types and lists of 181the `E` types. This makes our job easier. `mp_unique<mp_append<E1, E2>>` gives us the concatenation of `E1` and `E2` with the duplicates 182removed; we then add `common_type_t<T1, T2>` to the front via `mp_push_front`; and finally, we `mp_rename` the resultant `mp_list` 183to `expected`. 184 185## Fixing tuple_cat 186 187The article http://pdimov.com/cpp2/simple_cxx11_metaprogramming.html#[Simple C++11 metaprogramming] builds an 188implementation of the standard function `tuple_cat`, with the end result given below: 189 190``` 191template<class L> using F = mp_iota<mp_size<L>>; 192 193template<class R, class...Is, class... Ks, class Tp> 194R tuple_cat_( mp_list<Is...>, mp_list<Ks...>, Tp tp ) 195{ 196 return R{ std::get<Ks::value>(std::get<Is::value>(tp))... }; 197} 198 199template<class... Tp, 200 class R = mp_append<std::tuple<>, typename std::remove_reference<Tp>::type...>> 201 R tuple_cat( Tp &&... tp ) 202{ 203 std::size_t const N = sizeof...(Tp); 204 205 // inner 206 207 using list1 = mp_list< 208 mp_rename<typename std::remove_reference<Tp>::type, mp_list>...>; 209 210 using list2 = mp_iota_c<N>; 211 212 using list3 = mp_transform<mp_fill, list1, list2>; 213 214 using inner = mp_apply<mp_append, list3>; 215 216 // outer 217 218 using list4 = mp_transform<F, list1>; 219 220 using outer = mp_apply<mp_append, list4>; 221 222 // 223 224 return tuple_cat_<R>( inner(), outer(), 225 std::forward_as_tuple( std::forward<Tp>(tp)... ) ); 226} 227``` 228 229This function, however, is not entirely correct, in that it doesn't handle some cases properly. For example, 230trying to concatenate tuples containing move-only elements such as `unique_ptr` fails: 231 232``` 233std::tuple<std::unique_ptr<int>> t1; 234std::tuple<std::unique_ptr<float>> t2; 235 236auto result = ::tuple_cat( std::move( t1 ), std::move( t2 ) ); 237``` 238Trying to concatenate `const` tuples fails: 239``` 240std::tuple<int> const t1; 241std::tuple<float> const t2; 242 243auto result = ::tuple_cat( t1, t2 ); 244``` 245And finally, the standard `tuple_cat` is specified to work on arbitrary tuple-like types (that is, all types 246that support `tuple_size`, `tuple_element`, and `get`), while our implementation only works with `tuple` and 247`pair`. `std::array`, for example, fails: 248``` 249std::array<int, 2> t1{ 1, 2 }; 250std::array<float, 3> t2{ 3.0f, 4.0f, 5.0f }; 251 252auto result = ::tuple_cat( t1, t2 ); 253``` 254Let's fix these one by one. Support for move-only types is easy, if one knows where to look. The problem is 255that `Tp` that we're passing to the helper `tuple_cat_` is (correctly) `tuple<unique_ptr<int>&&, unique_ptr<float>&&>`, 256but `std::get<0>(tp)` still returns `unique_ptr<int>&`, because `tp` is an lvalue. This behavior is a bit 257surprising, but is intended to prevent inadvertent double moves. 258 259Long story short, we need `std::move(tp)` in `tuple_cat_` to make `tp` an rvalue: 260 261 template<class R, class...Is, class... Ks, class Tp> 262 R tuple_cat_( mp_list<Is...>, mp_list<Ks...>, Tp tp ) 263 { 264 return R{ std::get<Ks::value>(std::get<Is::value>(std::move(tp)))... }; 265 } 266 267Next, `const`-qualified tuples. The issue here is that we're stripping references from the input tuples, but not 268`const`. As a result, we're trying to manipulate types such as `tuple<int> const` with Mp11 algorithms, and these 269types do not fit the list concept. We just need to strip qualifiers as well, by defining the useful `remove_cv_ref` 270primitive that is inexplicably missing from the standard library: 271 272 template<class T> using remove_cv_ref = typename std::remove_cv< 273 typename std::remove_reference<T>::type>::type; 274 275and then by using `remove_cv_ref<Tp>` in place of `typename std::remove_reference<Tp>::type`: 276 277``` 278template<class... Tp, 279 class R = mp_append<std::tuple<>, remove_cv_ref<Tp>...>> 280 R tuple_cat( Tp &&... tp ) 281{ 282 std::size_t const N = sizeof...(Tp); 283 284 // inner 285 286 using list1 = mp_list<mp_rename<remove_cv_ref<Tp>, mp_list>...>; 287 288 // ... 289``` 290 291Finally, tuple-like types. We've so far exploited the fact that `std::pair` and `std::tuple` are valid Mp11 lists, 292but in general, arbitrary tuple-like types aren't, so we need to convert them into such. For that, we'll need to 293define a metafunction `from_tuple_like` that will take an arbitrary tuple-like type and will return, in our case, 294the corresponding `mp_list`. 295 296Technically, a more principled approach would've been to return `std::tuple`, but here `mp_list` will prove more 297convenient. 298 299What we need is, given a tuple-like type `Tp`, to obtain `mp_list<std::tuple_element<0, Tp>::type, std::tuple_element<1, Tp>::type, 300..., std::tuple_element<N-1, Tp>::type>`, where `N` is `tuple_size<Tp>::value`. Here's one way to do it: 301 302``` 303template<class T, class I> using tuple_element = 304 typename std::tuple_element<I::value, T>::type; 305 306template<class T> using from_tuple_like = 307 mp_product<tuple_element, mp_list<T>, mp_iota<std::tuple_size<T>>>; 308``` 309 310(`mp_iota<N>` is an algorithm that returns an `mp_list` with elements `mp_size_t<0>`, `mp_size_t<1>`, ..., `mp_size_t<N-1>`.) 311 312Remember that `mp_product<F, L1, L2>` performs the equivalent of two nested loops over the elements of `L1` and `L2`, 313applying `F` to the two variables and gathering the result. In our case `L1` consists of the single element `T`, so 314only the second loop (over `mp_iota<N>`, where `N` is `tuple_size<T>`), remains, and we get a list of the same type 315as `L1` (an `mp_list`) with contents `tuple_element<T, mp_size_t<0>>`, `tuple_element<T, mp_size_t<1>>`, ..., 316`tuple_element<T, mp_size_t<N-1>>`. 317 318For completeness's sake, here's another, more traditional way to achieve the same result: 319 320 template<class T> using from_tuple_like = 321 mp_transform_q<mp_bind_front<tuple_element, T>, mp_iota<std::tuple_size<T>>>; 322 323With all these fixes applied, our fully operational `tuple_cat` now looks like this: 324 325``` 326template<class L> using F = mp_iota<mp_size<L>>; 327 328template<class R, class...Is, class... Ks, class Tp> 329R tuple_cat_( mp_list<Is...>, mp_list<Ks...>, Tp tp ) 330{ 331 return R{ std::get<Ks::value>(std::get<Is::value>(std::move(tp)))... }; 332} 333 334template<class T> using remove_cv_ref = typename std::remove_cv< 335 typename std::remove_reference<T>::type>::type; 336 337template<class T, class I> using tuple_element = 338 typename std::tuple_element<I::value, T>::type; 339 340template<class T> using from_tuple_like = 341 mp_product<tuple_element, mp_list<T>, mp_iota<std::tuple_size<T>>>; 342 343template<class... Tp, 344 class R = mp_append<std::tuple<>, from_tuple_like<remove_cv_ref<Tp>>...>> 345 R tuple_cat( Tp &&... tp ) 346{ 347 std::size_t const N = sizeof...(Tp); 348 349 // inner 350 351 using list1 = mp_list<from_tuple_like<remove_cv_ref<Tp>>...>; 352 using list2 = mp_iota_c<N>; 353 354 using list3 = mp_transform<mp_fill, list1, list2>; 355 356 using inner = mp_apply<mp_append, list3>; 357 358 // outer 359 360 using list4 = mp_transform<F, list1>; 361 362 using outer = mp_apply<mp_append, list4>; 363 364 // 365 366 return tuple_cat_<R>( inner(), outer(), 367 std::forward_as_tuple( std::forward<Tp>(tp)... ) ); 368} 369``` 370 371## Computing Return Types 372 373{cpp}17 has a standard variant type, called `std::variant`. It also defines a function template 374`std::visit` that can be used to apply a function to the contained value of one or more variants. 375So for instance, if the variant `v1` contains `1`, and the variant `v2` contains `2.0f`, 376`std::visit(f, v1, v2)` will call `f(1, 2.0f)`. 377 378However, `std::visit` has one limitation: it cannot return a result unless all 379possible applications of the function have the same return type. If, for instance, `v1` and `v2` 380are both of type `std::variant<short, int, float>`, 381 382 std::visit( []( auto const& x, auto const& y ){ return x + y; }, v1, v2 ); 383 384will fail to compile because the result of `x + y` can be either `int` or `float` depending on 385what `v1` and `v2` hold. 386 387A type that can hold either `int` or `float` already exists, called, surprisingly enough, `std::variant<int, float>`. 388Let's write our own function template `rvisit` that is the same as `visit` but returns a `variant`: 389 390``` 391template<class F, class... V> auto rvisit( F&& f, V&&... v ) 392{ 393 using R = /*...*/; 394 395 return std::visit( [&]( auto&&... x ) 396 { return R( std::forward<F>(f)( std::forward<decltype(x)>(x)... ) ); }, 397 std::forward<V>( v )... ); 398} 399``` 400 401What this does is basically calls `std::visit` to do the work, but instead of passing it `f`, we pass a lambda that does the same as `f` except 402it converts the result to a common type `R`. `R` is supposed to be `std::variant<...>` where the ellipsis denotes the return types of 403calling `f` with all possible combinations of variant values. 404 405We'll first define a helper quoted metafunction `Qret<F>` that returns the result of the application of `F` to arguments of type `T...`: 406 407 template<class F> struct Qret 408 { 409 template<class... T> using fn = 410 decltype( std::declval<F>()( std::declval<T>()... ) ); 411 }; 412 413It turns out that {cpp}17 already contains a metafunction that returns the result of the application of a function `F` to arguments 414of type `T...`: `std::invoke_result_t<F, T...>`. We can make use of it to simplify our `Qret` to 415 416 template<class F> struct Qret 417 { 418 template<class... T> using fn = std::invoke_result_t<F, T...>; 419 }; 420 421which in Mp11 can be expressed more concisely as 422 423 using Qret = mp_bind_front<std::invoke_result_t, F>; 424 425With `Qret` in hand, a `variant` of the possible return types is just a matter of applying it over the possible combinations of the variant values: 426 427 using R = mp_product_q<Qret, remove_cv_ref<V>...>; 428 429Why does this work? `mp_product<F, L1<T1...>, L2<T2...>, ..., Ln<Tn...>>` returns `L1<F<U1, U2, ..., Un>, ...>`, where `Ui` traverse all 430possible combinations of list values. Since in our case all `Li` are `std::variant`, the result will also be `std::variant`. (`mp_product_q` is 431the same as `mp_product`, but for quoted metafunctions such as our `Qret`.) 432 433One more step remains. Suppose that, as above, we're passing two variants of type `std::variant<short, int, float>` and `F` is 434`[]( auto const& x, auto const& y ){ return x + y; }`. This will generate `R` of length 9, one per each combination, but many of those 435elements will be the same, either `int` or `float`, and we need to filter out the duplicates. So, we pass the result to `mp_unique`: 436 437 using R = mp_unique<mp_product_q<Qret, remove_cv_ref<V>...>>; 438 439and we're done: 440 441``` 442#include <boost/mp11.hpp> 443#include <boost/core/demangle.hpp> 444#include <variant> 445#include <type_traits> 446#include <typeinfo> 447#include <iostream> 448 449using namespace boost::mp11; 450 451template<class T> using remove_cv_ref = typename std::remove_cv< 452 typename std::remove_reference<T>::type>::type; 453 454template<class F, class... V> auto rvisit( F&& f, V&&... v ) 455{ 456 using Qret = mp_bind_front<std::invoke_result_t, F>; 457 458 using R = mp_unique<mp_product_q<Qret, remove_cv_ref<V>...>>; 459 460 return std::visit( [&]( auto&&... x ) 461 { return R( std::forward<F>(f)( std::forward<decltype(x)>(x)... ) ); }, 462 std::forward<V>( v )... ); 463} 464 465template<class T> std::string name() 466{ 467 return boost::core::demangle( typeid(T).name() ); 468} 469 470template<class V> void print_variant( char const * n, V const& v ) 471{ 472 std::cout << "(" << name<decltype(v)>() << ")" << n << ": "; 473 474 std::visit( []( auto const& x ) 475 { std::cout << "(" << name<decltype(x)>() << ")" << x << std::endl; }, v ); 476} 477 478int main() 479{ 480 std::variant<char, int, float> v1( 1 ); 481 482 print_variant( "v1", v1 ); 483 484 std::variant<short, int, double> const v2( 3.14 ); 485 486 print_variant( "v2", v2 ); 487 488 auto v3 = rvisit( []( auto const& x, auto const& y ){ return x + y; }, v1, v2 ); 489 490 print_variant( "v3", v3 ); 491} 492``` 493