di 0.1.0
Loading...
Searching...
No Matches
erasure_cast.h
Go to the documentation of this file.
1#pragma once
2
4#include "di/meta/language.h"
5#include "di/meta/trivial.h"
6#include "di/types/byte.h"
7#include "di/util/addressof.h"
8#include "di/util/bit_cast.h"
11
12namespace di::vocab::detail {
13template<concepts::TriviallyRelocatable To, concepts::TriviallyRelocatable From>
14requires(sizeof(To) == sizeof(From) && concepts::Trivial<From>)
15constexpr auto erasure_cast(From const& from) -> To {
16 return bit_cast<To>(from);
17}
18
19template<concepts::TriviallyRelocatable To, concepts::TriviallyRelocatable From>
20requires(sizeof(To) == sizeof(From) && concepts::RValueReference<From &&>)
21constexpr auto erasure_cast(From&& from) -> To {
22 if constexpr (requires { bit_cast<To>(from); }) {
23 return bit_cast<To>(from);
24 } else {
25 // This seems safe...
26 di::byte bytes[sizeof(From)];
27 di::copy((byte const*) di::addressof(from), (byte const*) di::addressof(from) + sizeof(From), bytes);
28 unsafe_forget(di::forward<From>(from));
29 return di::bit_cast<To>(bytes);
30 }
31}
32}
std::byte byte
Definition byte.h:64
constexpr auto unsafe_forget
Steal ownership of an object and do not its destructor.
Definition unsafe_forget.h:32
constexpr auto copy
Definition copy.h:30