Templatefunctiontoloadbigendianfrombytearray

I'm trying to implement template function, for reading from byte array in big endian order. This is my current implementation:

template<typename T>
T load_big_endian(const unsigned char* buf) {
  T res {};

  std::size_t size = sizeof(T) - 1;

  for (int i = 0; i <= size; i += 1) {
    res |= static_cast<T>(buf[size - i] << (i * 8));
  }

  return res;
}

Is this a good solution? Or better use a separate functions for each type, like load32_big_endian? And what problems can I face using this approach?

回答

Here's how I would do it:

#include <algorithm>
#include <cstddef>
#include <type_traits>

template <typename T>
[[nodiscard]] T load_big_endian(std::byte const* const buf) noexcept 
  requires std::is_trivial_v<T> 
{
  T res;
  std::reverse_copy(buf, buf + sizeof res, reinterpret_cast<std::byte*>(&res));
  return res;
}

Highlights:

  • std::byte conveys the intention more explicitly. You can still use unsigned char if that's a requirement, either will work.
  • reverse_copy is easier to use.
  • making sure that the type is trivial is a good idea to make sure we don't cause UB. You can loosen this restriction if needed.

以上是Templatefunctiontoloadbigendianfrombytearray的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>