使用模板元编程优化结构序列化

问题描述

我想在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 (将#修改为@)