Namespaces
Variants

std:: is_within_lifetime

From cppreference.net
Utilities library
Определено в заголовочном файле <type_traits>
template < class T >
consteval bool is_within_lifetime ( const T * ptr ) noexcept ;
(начиная с C++26)

Определяет, указывает ли указатель ptr на объект, который находится в пределах своего времени жизни .

При вычислении выражения E как core constant expression, вызов std::is_within_lifetime является ill-formed, если только ptr не указывает на объект

Содержание

Параметры

p - указатель для обнаружения

Возвращаемое значение

true если указатель ptr указывает на объект в пределах его времени жизни; в противном случае false .

Примечания

Макрос проверки возможностей Значение Стандарт Возможность
__cpp_lib_is_within_lifetime 202306L (C++26) Проверка активности альтернативы объединения

Пример

std::is_within_lifetime может использоваться для проверки, активен ли член объединения:

#include <type_traits>
// an optional boolean type occupying only one byte,
// assuming sizeof(bool) == sizeof(char)
struct optional_bool
{
    union { bool b; char c; };
    // assuming the value representations for true and false
    // are distinct from the value representation for 2
    constexpr optional_bool() : c(2) {}
    constexpr optional_bool(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*() -> bool&
    {
        return b;
    }
};
int main()
{
    constexpr optional_bool disengaged;
    constexpr optional_bool engaged(true);
    static_assert(!disengaged.has_value());
    static_assert(engaged.has_value());
    static_assert(*engaged);
}