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::byteconveys the intention more explicitly. You can still useunsigned charif that's a requirement, either will work.reverse_copyis 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.
THE END
二维码