[meta.const.eval]

# 21 Metaprogramming library [[meta]](./#meta)

## 21.3 Metaprogramming and type traits [[type.traits]](type.traits#meta.const.eval)

### 21.3.12 Constant evaluation context [meta.const.eval]

[ð](#lib:is_constant_evaluated)

`constexpr bool is_constant_evaluated() noexcept;
`

[1](#1)

[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/meta.tex#L2816)

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

[2](#2)

[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/meta.tex#L2827)

[*Example [1](#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*]

[ð](#lib:is_within_lifetime)

`consteval bool is_within_lifetime(const auto* p) noexcept;
`

[3](#3)

[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/meta.tex#L2847)

*Returns*: true if p is a pointer to an object that is
within its lifetime ([[basic.life]](basic.life "6.8.4 Lifetime")); otherwise, false[.](#3.sentence-1)

[4](#4)

[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/meta.tex#L2852)

*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[.](#4.sentence-1)

[5](#5)

[#](http://github.com/Eelis/draft/tree/9adde4bc1c62ec234483e63ea3b70a59724c745a/source/meta.tex#L2860)

[*Example [2](#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*]
