diff --git a/doc/mp11/examples.adoc b/doc/mp11/examples.adoc index 858bd55..176e8c3 100644 --- a/doc/mp11/examples.adoc +++ b/doc/mp11/examples.adoc @@ -370,7 +370,7 @@ template` that returns the resul decltype( std::declval()( std::declval()... ) ); }; -(Unfortunately, we can't just define this metafunction inside `rvisit`; the language prohibits defining template aliases inside functions.) +It turns out that {cpp}17 already contains a metafunction that returns the result of the application of a function `F` to arguments +of type `T...`: `std::invoke_result_t`. We can make use of it to simplify our `Qret` to + + template struct Qret + { + template using fn = std::invoke_result_t; + }; + +which in Mp11 can be expressed more concisely as + + using Qret = mp_bind_front; With `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: - using R = mp_product_q, std::remove_reference_t...>; + using R = mp_product_q...>; Why does this work? `mp_product, L2, ..., Ln>` returns `L1, ...>`, where `Ui` traverse all possible combinations of list values. Since in our case all `Li` are `std::variant`, the result will also be `std::variant`. (`mp_product_q` is -the same as `mp_product`, but for quoted metafunctions such as our `Qret`.) +the same as `mp_product`, but for quoted metafunctions such as our `Qret`.) One more step remains. Suppose that, as above, we're passing two variants of type `std::variant` and `F` is `[]( auto const& x, auto const& y ){ return x + y; }`. This will generate `R` of length 9, one per each combination, but many of those elements will be the same, either `int` or `float`, and we need to filter out the duplicates. So, we pass the result to `mp_unique`: - using R = mp_unique, std::remove_reference_t...>>; + using R = mp_unique...>>; and we're done: @@ -438,15 +448,14 @@ and we're done: using namespace boost::mp11; -template struct Qret -{ - template using fn = - decltype( std::declval()( std::declval()... ) ); -}; +template using remove_cv_ref = typename std::remove_cv< + typename std::remove_reference::type>::type; template auto rvisit( F&& f, V&&... v ) { - using R = mp_unique, std::remove_reference_t...>>; + using Qret = mp_bind_front; + + using R = mp_unique...>>; return std::visit( [&]( auto&&... x ) { return R( std::forward(f)( std::forward(x)... ) ); }, @@ -472,7 +481,7 @@ int main() print_variant( "v1", v1 ); - std::variant v2( 3.14 ); + std::variant const v2( 3.14 ); print_variant( "v2", v2 );