1 /* 2 * Copyright 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <type_traits> 20 #include <variant> 21 22 namespace android::ftl::details { 23 24 template <typename... Ms> 25 struct Matcher : Ms... { 26 using Ms::operator()...; 27 }; 28 29 // Deduction guide. 30 template <typename... Ms> 31 Matcher(Ms...) -> Matcher<Ms...>; 32 33 template <typename Matcher, typename... Ts> 34 constexpr bool is_exhaustive_match_v = (std::is_invocable_v<Matcher, Ts> && ...); 35 36 template <typename...> 37 struct Match; 38 39 template <typename T, typename U, typename... Ts> 40 struct Match<T, U, Ts...> { 41 template <typename Variant, typename Matcher> 42 static decltype(auto) match(Variant& variant, const Matcher& matcher) { 43 if (auto* const ptr = std::get_if<T>(&variant)) { 44 return matcher(*ptr); 45 } else { 46 return Match<U, Ts...>::match(variant, matcher); 47 } 48 } 49 }; 50 51 template <typename T> 52 struct Match<T> { 53 template <typename Variant, typename Matcher> 54 static decltype(auto) match(Variant& variant, const Matcher& matcher) { 55 return matcher(std::get<T>(variant)); 56 } 57 }; 58 59 } // namespace android::ftl::details 60