Files
cppdraft_translate/cppdraft/meta/const/eval.md
2025-10-25 03:02:53 +03:00

2.5 KiB

[meta.const.eval]

21 Metaprogramming library [meta]

21.3 Metaprogramming and type traits [type.traits]

21.3.12 Constant evaluation context [meta.const.eval]

🔗

constexpr bool is_constant_evaluated() noexcept;

1

#

Effects: Equivalent to:if consteval {return true;} else {return false;}

2

#

[Example 1: constexpr void f(unsigned char *p, int n) {if (std::is_constant_evaluated()) { // should not be a constexpr if statementfor (int k = 0; k<n; ++k) p[k] = 0; } else { memset(p, 0, n); // not a core constant expression}} — end example]

🔗

consteval bool is_within_lifetime(const auto* p) noexcept;

3

#

Returns: true if p is a pointer to an object that is within its lifetime ([basic.life]); otherwise, false.

4

#

Remarks: During the evaluation of an expression E as a core constant expression, a call to this function is ill-formed unless p points to an object that is usable in constant expressions or whose complete object's lifetime began within E.

5

#

[Example 2: struct OptBool {union { bool b; char c; }; // note: this assumes common implementation properties for bool and char:// * sizeof(bool) == sizeof(char), and// * the value representations for true and false are distinct// from the value representation for 2constexpr OptBool() : c(2) { }constexpr OptBool(bool b) : b(b) { }constexpr auto has_value() const -> bool {if consteval {return std::is_within_lifetime(&b); // during constant evaluation, cannot read from c} else {return c != 2; // during runtime, must read from c}}constexpr auto operator*() const -> const bool& {return b; }};

constexpr OptBool disengaged;constexpr OptBool engaged(true);static_assert(!disengaged.has_value());static_assert(engaged.has_value());static_assert(*engaged); — end example]