小编Pho*_*Oof的帖子

Cast raw bytes to any datatype

I'm worried if my implementation is unsafe or could be improved. Suppose I have an array of bytes (more specifically, std::byte); is casting an element's address to a void pointer and then to any datatype safe?

template <typename To>
constexpr To *byte_cast(std::byte &From) {
  return static_cast<To *>(static_cast<void *>(&From));
}

// or rather
template <typename To>
constexpr To *byte_cast(std::byte *From) {
  return static_cast<To *>(static_cast<void *>(From));
}
Run Code Online (Sandbox Code Playgroud)

I'm avoiding reinterpret_cast due to its unreliability. Do note that I want to the …

c++ reinterpret-cast c++17

3
推荐指数
1
解决办法
971
查看次数

标签 统计

c++ ×1

c++17 ×1

reinterpret-cast ×1