Skip to content

Commit

Permalink
[base] Add base::is_constant_evaluated()
Browse files Browse the repository at this point in the history
This change adds base::is_constant_evaluated(), a backport of C++20's
std::is_constant_evaluated(). Its intended use is within constexpr
functions, that can change their implementation depending on whether
or not they are constant evaluated.

Bug: None
Change-Id: I14a01c350d10fc8411fc5574889703af89b4c610
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2831596
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Commit-Queue: Jan Wilken Dörrie <jdoerrie@chromium.org>
Cr-Commit-Position: refs/heads/master@{#873925}
  • Loading branch information
jdoerrie authored and Chromium LUCI CQ committed Apr 19, 2021
1 parent b023d2a commit 2d7bca0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
14 changes: 14 additions & 0 deletions base/template_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <utility>
#include <vector>

#include "base/compiler_specific.h"
#include "build/build_config.h"

// Some versions of libstdc++ have partial support for type_traits, but misses
Expand Down Expand Up @@ -322,6 +323,19 @@ struct remove_cvref {
template <typename T>
using remove_cvref_t = typename remove_cvref<T>::type;

// Implementation of C++20's std::is_constant_evaluated.
//
// References:
// - https://en.cppreference.com/w/cpp/types/is_constant_evaluated
// - https://wg21.link/meta.const.eval
constexpr bool is_constant_evaluated() noexcept {
#if HAS_BUILTIN(__builtin_is_constant_evaluated)
return __builtin_is_constant_evaluated();
#else
return false;
#endif
}

// Simplified implementation of C++20's std::iter_value_t.
// As opposed to std::iter_value_t, this implementation does not restrict
// the type of `Iter` and does not consider specializations of
Expand Down
7 changes: 7 additions & 0 deletions base/template_util_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,13 @@ TEST(TemplateUtil, RemoveCvRefT) {
std::is_same<void (*)(int), remove_cvref_t<void (*)(int)>>::value, "");
}

TEST(TemplateUtil, IsConstantEvaluated) {
// base::is_constant_evaluated() should return whether it is evaluated as part
// of a constant expression.
static_assert(is_constant_evaluated(), "");
EXPECT_FALSE(is_constant_evaluated());
}

} // namespace

} // namespace base

0 comments on commit 2d7bca0

Please sign in to comment.