summaryrefslogtreecommitdiff
path: root/absl/meta/type_traits.h
diff options
context:
space:
mode:
authorGravatar Martijn Vels <mvels@google.com>2023-01-20 07:20:05 -0800
committerGravatar Copybara-Service <copybara-worker@google.com>2023-01-20 07:21:07 -0800
commita0b102c35bae9dea68be21a718c8c7b459e239c8 (patch)
tree9123391c09f15b2f49ea725636d2b449796dad20 /absl/meta/type_traits.h
parentc611e5ce1de222eb995f5aeabf3fa8cd57ae124b (diff)
Add absl::is_constant_evaluated for pre-c++20 support
PiperOrigin-RevId: 503437019 Change-Id: I3630fec690f1472130fef21b16dfcd3c5208aa69
Diffstat (limited to 'absl/meta/type_traits.h')
-rw-r--r--absl/meta/type_traits.h39
1 files changed, 39 insertions, 0 deletions
diff --git a/absl/meta/type_traits.h b/absl/meta/type_traits.h
index dd9de42f..b1656c39 100644
--- a/absl/meta/type_traits.h
+++ b/absl/meta/type_traits.h
@@ -844,6 +844,45 @@ template <class T>
struct is_trivially_relocatable : std::integral_constant<bool, false> {};
#endif
+// absl::is_constant_evaluated()
+//
+// Detects whether the function call occurs within a constant-evaluated context.
+// Returns true if the evaluation of the call occurs within the evaluation of an
+// expression or conversion that is manifestly constant-evaluated; otherwise
+// returns false.
+//
+// This function is implemented in terms of `std::is_constant_evaluated` for
+// c++20 and up. For older c++ versions, the function is implemented in terms
+// of `__builtin_is_constant_evaluated` if available, otherwise the function
+// will fail to compile.
+//
+// Applications can inspect `ABSL_HAVE_CONSTANT_EVALUATED` at compile time
+// to check if this function is supported.
+//
+// Example:
+//
+// constexpr MyClass::MyClass(int param) {
+// #ifdef ABSL_HAVE_CONSTANT_EVALUATED
+// if (!absl::is_constant_evaluated()) {
+// ABSL_LOG(INFO) << "MyClass(" << param << ")";
+// }
+// #endif // ABSL_HAVE_CONSTANT_EVALUATED
+// }
+//
+// Upstream documentation:
+//
+// http://en.cppreference.com/w/cpp/types/is_constant_evaluated
+// http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#:~:text=__builtin_is_constant_evaluated
+//
+#if defined(ABSL_HAVE_CONSTANT_EVALUATED)
+constexpr bool is_constant_evaluated() noexcept {
+#ifdef __cpp_lib_is_constant_evaluated
+ return std::is_constant_evaluated();
+#elif ABSL_HAVE_BUILTIN(__builtin_is_constant_evaluated)
+ return __builtin_is_constant_evaluated();
+#endif
+}
+#endif // ABSL_HAVE_CONSTANT_EVALUATED
ABSL_NAMESPACE_END
} // namespace absl