我正在尝试实现模板函数,用于以大端序读取字节数组。这是我目前的实现方式:
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;
}
这是一个好的解决方案吗?或者更好地为每种类型使用单独的函数,如load32_big_endian
?使用这种方法我会遇到什么问题?
以下是我的操作方法:
#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;
}
亮点:
std::byte
更明确地传达了意图。如果需要,您仍然可以使用unsigned char
,两者都可以reverse_copy
更易于使用- 确保类型是琐碎的是一个好主意,以确保我们不会导致UB。如果需要,您可以放宽此限制