1 // Copyright 2023 The Abseil 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 // https://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 // -----------------------------------------------------------------------------
16 // File: overload.h
17 // -----------------------------------------------------------------------------
18 //
19 // `absl::Overload()` returns a functor that provides overloads based on the
20 // functors passed to it.
21 // Before using this function, consider whether named function overloads would
22 // be a better design.
23 // One use case for this is locally defining visitors for `std::visit` inside a
24 // function using lambdas.
25
26 // Example: Using `absl::Overload` to define a visitor for `std::variant`.
27 //
28 // std::variant<int, std::string, double> v(int{1});
29 //
30 // assert(std::visit(absl::Overload(
31 // [](int) -> absl::string_view { return "int"; },
32 // [](const std::string&) -> absl::string_view {
33 // return "string";
34 // },
35 // [](double) -> absl::string_view { return "double"; }),
36 // v) == "int");
37 //
38 // Note: This requires C++17.
39
40 #ifndef ABSL_FUNCTIONAL_OVERLOAD_H_
41 #define ABSL_FUNCTIONAL_OVERLOAD_H_
42
43 #include "absl/base/config.h"
44 #include "absl/meta/type_traits.h"
45
46 namespace absl {
47 ABSL_NAMESPACE_BEGIN
48
49 #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \
50 ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L
51
52 template <int&... ExplicitArgumentBarrier, typename... T>
Overload(T &&...ts)53 auto Overload(T&&... ts) {
54 struct OverloadImpl : absl::remove_cvref_t<T>... {
55 using absl::remove_cvref_t<T>::operator()...;
56 };
57 return OverloadImpl{std::forward<T>(ts)...};
58 }
59 #else
60 namespace functional_internal {
61 template <typename T>
62 constexpr bool kDependentFalse = false;
63 }
64
65 template <typename Dependent = int, typename... T>
66 auto Overload(T&&...) {
67 static_assert(functional_internal::kDependentFalse<Dependent>,
68 "Overload is only usable with C++17 or above.");
69 }
70
71 #endif
72 ABSL_NAMESPACE_END
73 } // namespace absl
74
75 #endif // ABSL_FUNCTIONAL_OVERLOAD_H_
76