如何通过网络序列化和发送 std::list? [英] How can I serialize and send a std::list over the network?

查看:28
本文介绍了如何通过网络序列化和发送 std::list?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过网络连接发送存储在 std::list 中的动态大小的数据列表.我想使用序列化一次性完成此操作,而不是单独发送每个元素.有什么建议吗?

I need to send a dynamically sized list of data stored inside a std::list over a network connection. I would like to do this in one pass using serialization, rather than sending each element individually. Any suggestions?

推荐答案

boost::serialization 使这很容易做到.它免费提供了 std::list 所需的所有机制,您需要做的就是添加对列表类型的支持.(如果它是标准"类型,它也已经存在)

boost::serialization makes this fairly easy to do. It provides all of the mechanics you need for std::list for free, all you will need to do is add support to the type your list holds. (If it's a "standard" type this will already exist too)

完整示例(改编自这个示例):

#include <list>
#include <sstream>

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
// Provide an implementation of serialize for std::list
#include <boost/serialization/list.hpp>

class foo
{
private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive & ar, const unsigned int /*version*/)
  {
    // This is the only thing you have to implement to serialize a std::list<foo>
    ar & value;
    // if we had more members here just & each of them with ar
  }
public:
  int value;
};

int main() {
  std::stringstream out;

  // setup a list
  std::list<foo> list;
  {
    const foo f = {-1};
    list.push_back(f);
  }

  // serialize into the stream
  {
    boost::archive::binary_oarchive oa(out);
    oa << list;
  }

  // read the stream into a newlist
  std::list<foo> newlist;
  {
    boost::archive::binary_iarchive ia(out);
    ia >> newlist;
  }

  std::cout << newlist.front().value << std::endl;
}

这通过std::stringstream发送"和接收",但调整它以通过您选择的网络API发送和接收应该是相当简单的.

This "sends" and "receives" via a std::stringstream, but it should be fairly trivial to adapt this to send and receive via the network API of your choice.

这篇关于如何通过网络序列化和发送 std::list?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆