| 37 | typename... Cases |
| 38 | > |
| 39 | constexpr decltype(auto) switch_( |
| 40 | types_<T...> /*meta_obj*/, |
| 41 | Cases&&... cases |
| 42 | ) |
| 43 | /*! |
| 44 | requires |
| 45 | - meta_obj combines a set of initial types. These are used as compile-time initial conditions. |
| 46 | - cases is a set of overload-able conditional branches. |
| 47 | - at least one of the cases is callable given meta_obj. |
| 48 | - each case statement has signature auto(types_<>..., auto _) where _ is an identity function |
| 49 | with identical behaviour to std::identity. This is used to make each generic lambda artificially |
| 50 | dependent on the function body. This allows semantic analysis of the lambdas to be performed AFTER |
| 51 | the correct lambda is chosen depending on meta_obj. This is the crucial bit that makes switch_() behave |
| 52 | in a similar way to "if constexpr()" in C++17. Make sure to use _ on one of the objects in the lambdas. |
| 53 | ensures |
| 54 | - calls the correct conditional branch. |
| 55 | - the correct conditional branch is selected at compile-time. |
| 56 | - Note, each branch can return different types, and the return type of the switch_() function |
| 57 | is that of the compile-time selected branch. |
| 58 | |
| 59 | Here is an example: |
| 60 | |
| 61 | template<typename T> |
| 62 | auto perform_correct_action(T& obj) |
| 63 | { |
| 64 | return switch_( |
| 65 | types_<T>{}, |
| 66 | [&](types_<A>, auto _) { |
| 67 | return _(obj).set_something_specific_to_A_and_return_something(); |
| 68 | }, |
| 69 | [&](types_<B>, auto _) { |
| 70 | return _(obj).set_something_specific_to_B_and_return_something(); |
| 71 | }, |
| 72 | [&](auto...) { |
| 73 | // Default case statement. Do something sensible. |
| 74 | return false; |
| 75 | } |
| 76 | ); |
| 77 | } |
| 78 | |
| 79 | Here is another example: |
| 80 | |
| 81 | template<typename T> |
| 82 | auto transfer_state(T& a, T& b) |
| 83 | { |
| 84 | return switch_( |
| 85 | bools(std::is_move_constructible<T>{}, std::is_copy_constructible<T>{}), |
| 86 | [&](true_t, auto, auto _) { |
| 87 | // T is both move-constructible. Copy semantics can be anything |
| 88 | a = std::move(_(b)); |
| 89 | return move_tag{}; // Just for fun, we return different types in each branch. |
| 90 | }, |
| 91 | [&](auto, true_t, auto _) { |
| 92 | // T is copy-constructible, Move semantics can be anything. Though in this case, |
| 93 | // if it had been move-constructible, the first branch would have been selected. |
| 94 | // So in this case, it is not move-constructible. |
| 95 | a = _(b); |
| 96 | return copy_tag{}; |