C++ Logo

std-proposals

Advanced search

Re: [std-proposals] [[packed]] std::unaligned

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Wed, 13 Dec 2023 17:55:22 +0000
On Wed, Dec 13, 2023 at 4:03 PM connor horman wrote:
>
> As a note, the non-trivial versions have consistently been non-`constexpr`.
> I think that it would be beneficial to support constant initialization of `unaligned<T>`
> globals. This requires the use of `std::bit_cast`, not `std::memcpy`, which includes
> a constraint of `std::trivially_copyable<T>`.


If we ignore that bit_cast is constexpr, then a possible
implementation would be:

        template<class To, class From>
        requires ( sizeof(To) == sizeof(From) )
        // constexpr support needs compiler magic
        constexpr To bit_cast(From const &src) noexcept
        {
            return *static_cast<To const*>(static_cast<void const*>(&src));
        }

I think we could do with having a similar function based on __datasizeof:

        template<class To, class From>
        requires ( __datasizeof(To) <= sizeof(From) )
        // constexpr support needs compiler magic
        constexpr To bit_cast_potentially_overlapping(From const &src) noexcept
        {
            return *static_cast<To const*>(static_cast<void const*>(&src));
        }

Received on 2023-12-13 17:55:24