From 0d66b5a135f3e56041e0252e1f6d7cf8f598c8c2 Mon Sep 17 00:00:00 2001 From: ADAM David Alan Martin Date: Fri, 10 Nov 2023 23:15:37 -0500 Subject: [PATCH] This should be in C++23, but some compilers/libraries still lack it. --- lifetime.h | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 lifetime.h diff --git a/lifetime.h b/lifetime.h new file mode 100644 index 0000000..aa44f0e --- /dev/null +++ b/lifetime.h @@ -0,0 +1,39 @@ +static_assert( __cplusplus > 2020'00 ); + +#pragma once + +#include + +#include + +#include + +namespace Alepha::Hydrogen ::detail:: lifetime_m +{ + inline namespace exports + { + // When C++23 arrives, just turn these into `using` statements. + + template< typename T > + std::add_pointer_t< T > + start_lifetime_as( void *const mp ) noexcept + { + const auto raw= new( mp ) std::byte[ sizeof( T ) ]; + const auto data= reinterpret_cast< std::add_pointer_t< T > >( raw ); + return std::launder( data ); + } + + template< typename T > + std::add_pointer_t< std::add_const_t< T > > + start_lifetime_as( const void *const p ) noexcept + { + const auto mp= const_cast< void * >( p ); + return start_lifetime_as< std::add_const_t< T > >( mp ); + } + } +} + +namespace Alepha::Hydrogen::inline exports::inline lifetime_m +{ + using namespace detail::lifetime_m::exports; +}