xref: /aosp_15_r20/external/abseil-cpp/absl/utility/internal/if_constexpr.h (revision 9356374a3709195abf420251b3e825997ff56c0f)
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 // The IfConstexpr and IfConstexprElse utilities in this file are meant to be
16 // used to emulate `if constexpr` in pre-C++17 mode in library implementation.
17 // The motivation is to allow for avoiding complex SFINAE.
18 //
19 // The functions passed in must depend on the type(s) of the object(s) that
20 // require SFINAE. For example:
21 // template<typename T>
22 // int MaybeFoo(T& t) {
23 //   if constexpr (HasFoo<T>::value) return t.foo();
24 //   return 0;
25 // }
26 //
27 // can be written in pre-C++17 as:
28 //
29 // template<typename T>
30 // int MaybeFoo(T& t) {
31 //   int i = 0;
32 //   absl::utility_internal::IfConstexpr<HasFoo<T>::value>(
33 //       [&](const auto& fooer) { i = fooer.foo(); }, t);
34 //   return i;
35 // }
36 
37 #ifndef ABSL_UTILITY_INTERNAL_IF_CONSTEXPR_H_
38 #define ABSL_UTILITY_INTERNAL_IF_CONSTEXPR_H_
39 
40 #include <tuple>
41 #include <utility>
42 
43 #include "absl/base/config.h"
44 
45 namespace absl {
46 ABSL_NAMESPACE_BEGIN
47 
48 namespace utility_internal {
49 
50 template <bool condition, typename TrueFunc, typename FalseFunc,
51           typename... Args>
IfConstexprElse(TrueFunc && true_func,FalseFunc && false_func,Args &&...args)52 auto IfConstexprElse(TrueFunc&& true_func, FalseFunc&& false_func,
53                      Args&&... args) {
54   return std::get<condition>(std::forward_as_tuple(
55       std::forward<FalseFunc>(false_func), std::forward<TrueFunc>(true_func)))(
56       std::forward<Args>(args)...);
57 }
58 
59 template <bool condition, typename Func, typename... Args>
IfConstexpr(Func && func,Args &&...args)60 void IfConstexpr(Func&& func, Args&&... args) {
61   IfConstexprElse<condition>(std::forward<Func>(func), [](auto&&...){},
62                              std::forward<Args>(args)...);
63 }
64 
65 }  // namespace utility_internal
66 
67 ABSL_NAMESPACE_END
68 }  // namespace absl
69 
70 #endif  // ABSL_UTILITY_INTERNAL_IF_CONSTEXPR_H_
71