如何解决使用模板元编程优化结构序列化
我想在32位对齐平台(armv7)上序列化结构。想法是将结构成员(我提取了with some meta programming)序列化为std::byte
数组,然后将其复制到std::uint32_t
数组(输出缓冲区)中。
两个序列化器如下所示:
// serialize to std::byte array
template <typename T,class OutputIterator,typename std::enable_if_t<
std::is_same<typename std::iterator_traits<OutputIterator>::value_type,std::byte>::value,int> = 0>
std::size_t serialize(const T& value,OutputIterator iterator)
{
std::size_t offset = 0;
visit_struct::for_each(value,[&](const char*,const auto& element)
{
auto raw = reinterpret_cast<std::byte const*>(&element);
auto type_size = sizeof(decltype(element));
std::copy(raw,std::next(raw,type_size),std::next(iterator,offset));
offset += type_size;
});
return offset;
}
// serialize to std::uint32_t array
template <typename T,std::uint32_t>::value,OutputIterator iterator)
{
constexpr std::size_t type_size = ext::mock_maker<T>::size;
constexpr std::size_t aligned_type_size = (type_size + 4 - 1) / 4;
std::array<std::byte,type_size> raw;
serialize(value,raw.begin());
auto raw_aligned = reinterpret_cast<std::uint32_t const*>(raw.data());
std::copy(raw_aligned,std::next(raw_aligned,aligned_type_size),iterator);
return aligned_type_size;
}
我希望编译器可以以某种方式优化中间表示形式的std::byte
数组,但是我的test implementation却建议。有没有办法优雅地实现这一目标?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。