Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:27:31

0001 // Copyright 2023 The Abseil Authors
0002 //
0003 // Licensed under the Apache License, Version 2.0 (the "License");
0004 // you may not use this file except in compliance with the License.
0005 // You may obtain a copy of the License at
0006 //
0007 //     https://www.apache.org/licenses/LICENSE-2.0
0008 //
0009 // Unless required by applicable law or agreed to in writing, software
0010 // distributed under the License is distributed on an "AS IS" BASIS,
0011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0012 // See the License for the specific language governing permissions and
0013 // limitations under the License.
0014 
0015 // The IfConstexpr and IfConstexprElse utilities in this file are meant to be
0016 // used to emulate `if constexpr` in pre-C++17 mode in library implementation.
0017 // The motivation is to allow for avoiding complex SFINAE.
0018 //
0019 // The functions passed in must depend on the type(s) of the object(s) that
0020 // require SFINAE. For example:
0021 // template<typename T>
0022 // int MaybeFoo(T& t) {
0023 //   if constexpr (HasFoo<T>::value) return t.foo();
0024 //   return 0;
0025 // }
0026 //
0027 // can be written in pre-C++17 as:
0028 //
0029 // template<typename T>
0030 // int MaybeFoo(T& t) {
0031 //   int i = 0;
0032 //   absl::utility_internal::IfConstexpr<HasFoo<T>::value>(
0033 //       [&](const auto& fooer) { i = fooer.foo(); }, t);
0034 //   return i;
0035 // }
0036 
0037 #ifndef ABSL_UTILITY_INTERNAL_IF_CONSTEXPR_H_
0038 #define ABSL_UTILITY_INTERNAL_IF_CONSTEXPR_H_
0039 
0040 #include <tuple>
0041 #include <utility>
0042 
0043 #include "absl/base/config.h"
0044 
0045 namespace absl {
0046 ABSL_NAMESPACE_BEGIN
0047 
0048 namespace utility_internal {
0049 
0050 template <bool condition, typename TrueFunc, typename FalseFunc,
0051           typename... Args>
0052 auto IfConstexprElse(TrueFunc&& true_func, FalseFunc&& false_func,
0053                      Args&&... args) {
0054   return std::get<condition>(std::forward_as_tuple(
0055       std::forward<FalseFunc>(false_func), std::forward<TrueFunc>(true_func)))(
0056       std::forward<Args>(args)...);
0057 }
0058 
0059 template <bool condition, typename Func, typename... Args>
0060 void IfConstexpr(Func&& func, Args&&... args) {
0061   IfConstexprElse<condition>(std::forward<Func>(func), [](auto&&...){},
0062                              std::forward<Args>(args)...);
0063 }
0064 
0065 }  // namespace utility_internal
0066 
0067 ABSL_NAMESPACE_END
0068 }  // namespace absl
0069 
0070 #endif  // ABSL_UTILITY_INTERNAL_IF_CONSTEXPR_H_