• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef GRPC_SRC_CORE_LIB_GPRPP_OVERLOAD_H
16 #define GRPC_SRC_CORE_LIB_GPRPP_OVERLOAD_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <utility>
21 
22 namespace grpc_core {
23 
24 template <typename... Cases>
25 struct OverloadType;
26 // Compose one overload with N more -- use inheritance to leverage using and the
27 // empty base class optimization.
28 template <typename Case, typename... Cases>
29 struct OverloadType<Case, Cases...> : public Case,
30                                       public OverloadType<Cases...> {
31   explicit OverloadType(Case&& c, Cases&&... cases)
32       : Case(std::forward<Case>(c)),
33         OverloadType<Cases...>(std::forward<Cases>(cases)...) {}
34   using Case::operator();
35   using OverloadType<Cases...>::operator();
36 };
37 // Overload of a single case is just that case itself
38 template <typename Case>
39 struct OverloadType<Case> : public Case {
40   explicit OverloadType(Case&& c) : Case(std::forward<Case>(c)) {}
41   using Case::operator();
42 };
43 
44 /// Compose callables into a single callable.
45 /// e.g. given [](int i) { puts("a"); } and [](double d) { puts("b"); },
46 /// return a callable object like:
47 /// struct {
48 ///   void operator()(int i) { puts("a"); }
49 ///   void operator()(double i) { puts("b"); }
50 /// };
51 /// Preserves all captures.
52 template <typename... Cases>
53 OverloadType<Cases...> Overload(Cases... cases) {
54   return OverloadType<Cases...>(std::move(cases)...);
55 }
56 
57 }  // namespace grpc_core
58 
59 #endif  // GRPC_SRC_CORE_LIB_GPRPP_OVERLOAD_H
60