I understand that copying arbitrary chunks of memory is not always possible to do at compile time but since we are getting constexpr containers, virtual methods and also algorithms, why not memcpy too? It is too a kind of algorithm.
Furthemore,
- C++20
std::bit_cast
seems a lot likestd::memcpy
workaroundreinterpret_cast
but it isconstexpr
. std::copy
using iterators is marked asconstexpr
for C++20, so copying is somehow possible for types.
The usage would be to either copy or just "reinterpret" variables/arrays in constexpr
functions, the former is not solved by std::bit_cast
AFAIK. In particular, the question and my answer would like to use it.
- Is there any particular reason for why
std::bit_cast
can be constexpr butstd::memcpy
cannot? - Does it have to do with memcpy using void pointers instead of typed references?
- Not actually having to copy anything?
- C backwards compatibility?
- Maybe because there is no support for a "pointer to constexpr memory"? But the same applies to the reference parameter in
std::bit_cast
and iterators instd::copy
.
Relevant answer to C++20 bit_cast vs reinterpret_cast briefly cites from somewhere:
Furthermore, it is currently impossible to implement a constexpr bit-cast function, as memcpy itself isn’t constexpr. Marking the proposed function as constexpr doesn’t require or prevent memcpy from becoming constexpr, but requires compiler support. This leaves implementations free to use their own internal solution (e.g. LLVM has a bitcast opcode).
But it does not go into detail of not making it constexpr too.
Note, that I do not ask for why std::bit_cast
exists. I like it, it provides a clear intention instead of std::memcpy
workaround.