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 // One of the lambda may specify overload for several types via generic lambda.
39 //
40 // absl::variant<std::string, int32_t, int64_t> v(int32_t{1});
41 // assert(std::visit(absl::Overload(
42 // [](const std::string& s) { return s.size(); },
43 // [](const auto& s) { return sizeof(s); }), v) == 4);
44 //
45 // Note: absl::Overload requires C++17.
46
47 #ifndef ABSL_FUNCTIONAL_OVERLOAD_H_
48 #define ABSL_FUNCTIONAL_OVERLOAD_H_
49
50 #include "absl/base/config.h"
51 #include "absl/meta/type_traits.h"
52
53 namespace absl {
54 ABSL_NAMESPACE_BEGIN
55
56 #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \
57 ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L
58
59 template <int&... ExplicitArgumentBarrier, typename... T>
Overload(T &&...ts)60 auto Overload(T&&... ts) {
61 struct OverloadImpl : absl::remove_cvref_t<T>... {
62 using absl::remove_cvref_t<T>::operator()...;
63 };
64 return OverloadImpl{std::forward<T>(ts)...};
65 }
66 #else
67 namespace functional_internal {
68 template <typename T>
69 constexpr bool kDependentFalse = false;
70 }
71
72 template <typename Dependent = int, typename... T>
73 auto Overload(T&&...) {
74 static_assert(functional_internal::kDependentFalse<Dependent>,
75 "Overload is only usable with C++17 or above.");
76 }
77
78 #endif
79 ABSL_NAMESPACE_END
80 } // namespace absl
81
82 #endif // ABSL_FUNCTIONAL_OVERLOAD_H_
83